Binary Tree Level Order Traversal II
Binary Tree Level Order Traversal II
题目
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
思路
跟Binary Tree Level Order Traversal思路一样,只不过在最后一步反转一下就OK了。
解题
c++版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42/**
* 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) {
vector<vector<int>> result;
if(!root)
return result;
vector<int> res;
queue<TreeNode*> que;
que.push(root);
int count=que.size();
while(!que.empty()){
TreeNode* tmp=que.front();
que.pop();
count--;
res.push_back(tmp->val);
if(tmp->left)
que.push(tmp->left);
if(tmp->right)
que.push(tmp->right);
if(count==0){
result.push_back(res);
count=que.size();
res.clear();
}
}
for(int i=0;i<result.size()/2;i++){
vector<int> tmp=result[i];
result[i]=result[result.size()-1-i];
result[result.size()-1-i]=tmp;
}
return result;
}
};
python版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrderBottom(self, root):
if not root:
return []
result=[]
queue=[]
queue.append(root)
count=len(queue)
s=[]
while len(queue)!=0:
tmp=queue[0]
s.append(tmp.val)
del queue[0]
count-=1
if tmp.left:
queue.append(tmp.left)
if tmp.right:
queue.append(tmp.right)
if count==0:
result.append(s)
s=[]
count=len(queue)
for i in range(len(result)/2):
tmp=result[i]
result[i]=result[len(result)-i-1]
result[len(result)-i-1]=tmp
return result