LeetCode - 二叉树的层序遍历 II

描述:给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

思路:用二叉树的层次遍历(借助队列),并将每层的结果压入中,最后将栈中元素出栈放入到动态数组中。

代码:

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;
    }
};

猜你喜欢

转载自blog.csdn.net/sinat_41721615/article/details/121604265