【题目描述】
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是一样的,不过是最后插入的时候上一题是从尾部插入,这一道是从头部插而已。
【代码】
/**
* 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==NULL) return {};
vector<vector<int>> ans;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
vector<int> p;
int len=q.size();
for(int i=0;i<len;i++){
TreeNode* node=q.front();
p.push_back(node->val);
if(node->left!=NULL) q.push(node->left);
if(node->right!=NULL) q.push(node->right);
q.pop();
}
ans.insert(ans.begin(),p);
}
return ans;
}
};