Description
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).
Example
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
Solution 1(C++)
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> layer;
if(!root) return res;
layer.push(root);
while(!layer.empty()){
int len=layer.size();
vector<int> laynum;
for(; len>0; len--){
TreeNode* temp=layer.front();
layer.pop();
if(temp->left) layer.push(temp->left);
if(temp->right) layer.push(temp->right);
laynum.push_back(temp->val);
}
res.push_back(laynum);
}
reverse(res.begin(), res.end());
return res;
}
};
算法分析
这道题也不用多说,先掌握这一种解法即可。可以与: LeetCode-637. Average of Levels in Binary Tree 联合起来看。
程序分析
要掌握按层遍历二叉树的方法。
queue<TreeNode*> layer;
//if(!root) return;
layer.push(root);
while(!layer.empty()){
int len=layer.size();
for(; len>0; len--){
TreeNode* temp=layer.front();
layer.pop();
if(temp->left) layer.push(temp->left);
if(temp->right) layer.push(temp->right);
}
}