您的位置:首页 > 编程语言 > C语言/C++

Binary Tree Level Order Traversal II

2016-06-10 23:11 447 查看

c++

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {

if (root == nullptr)
return vector<vector<int>>(0);
vector<vector<int>> res;
getLeaf(root, res, 0);
reverse(res.begin(), res.end());
return res;
}
private:
void getLeaf(const TreeNode* root, vector<vector<int>> &res, int depth) {
depth++;
if (res.size() < depth) {
vector<int> tmp(1,root->val);
res.push_back(tmp);
}
else {
res[depth - 1].push_back(root->val);
}
if (root->left == nullptr && root->right == nullptr)
return;
if (root->left != nullptr)
getLeaf(root->left, res, depth);
if (root->right != nullptr)
getLeaf(root->right, res, depth);
}
};


python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
res = []
self.getLeaf(root, res, 0)

return res[::-1]

def getLeaf(self, root, res, depth):
depth += 1
if len(res) < depth:
tmp = [root.val]
res.append(tmp)
else:
res[depth-1].append(root.val)

if not root.left and not root.right:
return
if root.left:
self.getLeaf(root.left, res, depth)
if root.right:
self.getLeaf(root.right, res, depth)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言