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]
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]
]
问题分析:这个问题和问题一的不同之处就是,这里需要的是倒序的,看到倒序我就想到了栈,于是这里和之前的题目的区别就在于这里多使用了一个栈来中转一下,多了一步最终的出栈过程,其他的思路和之前问题一的处理方式类似,用另外一个队列来辅助保存每一层的数据,实现代码如下:
/**
* 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 {
stack<vector<int>> stk;
queue<TreeNode*> que1;
queue<TreeNode*> que2;
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> vtOuter;
vector<int> vtInner;
if(root==NULL) return vtOuter;
TreeNode *p=root;
que1.push(root);
while(!que1.empty()||!que2.empty()){
while(!que1.empty()){
TreeNode *q=que1.front();
vtInner.push_back(q->val);
que1.pop();
if(q->left!=NULL) que2.push(q->left);
if(q->right!=NULL) que2.push(q->right);
}
if(!vtInner.empty()){
stk.push(vtInner);
vtInner.clear();
}
while(!que2.empty()){
TreeNode *q=que2.front();
vtInner.push_back(q->val);
que2.pop();
if(q->left!=NULL) que1.push(q->left);
if(q->right!=NULL) que1.push(q->right);
}
if(!vtInner.empty()){
stk.push(vtInner);
vtInner.clear();
}
}
while(!stk.empty()){
vtOuter.push_back(stk.top());
stk.pop();
}
return vtOuter;
}
};