(leetcode)107. 二叉树的层次遍历 II

参考blog:https://www.cnblogs.com/Allen-rg/p/7102351.html

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

例如:给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其自底向上的层次遍历为:

[
  [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 {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> retVec;//返回的双重向量
        if(!root)   return retVec;
        stack<vector<int>> myStack;//临时存储vector<int>类型变量的栈
        queue<TreeNode*> myQueue;   //TreeNode*类型的队列
        myQueue.push(root);
        while(!myQueue.empty()){
            int size = myQueue.size();
            vector<int> tempVec;
            while(size-- > 0){
                TreeNode* top = myQueue.front();
                tempVec.push_back(top->val);
                myQueue.pop();
                //应该是每次pop出来之后都把相应的左孩子和右孩子加进去
                if(top->left){
                    myQueue.push(top->left);
                }
                if(top->right){
                    myQueue.push(top->right);
                }   
            }
           myStack.push(tempVec);
        }
        while(!myStack.empty()){
            //栈中元素转移至retVec,此时顺序正常
            retVec.push_back(myStack.top());
            myStack.pop();
        }
        return retVec;
    }
};

算法分析:

之前写的层次遍历只是单纯的输出在一个数组或者向量中,结果本道题目的要求是按层次保存在双重向量中

所以基本思路依然是:在指针队列不为空的情况下进行节点指针的出队入队操作

只是如何保存数据呢?其实每一轮pop之前记一下此时的队列大小(元素个数)即可,具体请看代码。

另外还有一个点就是要求的返回值其实是逆序的,所以我根据栈的后入先出的特点先保存在栈里再往retVec里转移

但是参考博客里的大佬直接用了一个向量的reverse函数就OK了,如果C++写的话可以查一下相应的函数!!

OK,欢迎评论!!!

猜你喜欢

转载自blog.csdn.net/liuxiang15/article/details/82354520