描述:给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
思路:用二叉树的层次遍历(借助队列),并将每层的结果压入栈中,最后将栈中元素出栈放入到动态数组中。
代码:
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
//use stack and queue push
vector<vector<int>> res;
stack<vector<int>> stk;
queue<TreeNode*> que;
TreeNode* p = root;
que.push(p);
while(p!=NULL && !que.empty()){
vector<int> tmp;
int n = que.size();
for(int i=0;i<n;i++){
p = que.front();
que.pop();
tmp.push_back(p->val);
if(p->left!=NULL){
que.push(p->left);
}
if(p->right!=NULL){
que.push(p->right);
}
}
stk.push(tmp);
}
while(!stk.empty()){
vector<int> tmp = stk.top();
stk.pop();
res.push_back(tmp);
}
return res;
}
};