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

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

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

    3
   / \
  9  20
    /  \
   15   7

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

[
  [15,7],
  [9,20],
  [3]
]

思路

正常BFS+reverse即可
code

    /**
     * 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) {
            queue<TreeNode*> q;
            vector<vector<int>> all;
            if(!root)
                return all;
            q.push(root);
            while(!q.empty()){
                int len = q.size();
                vector<int> aaa;
                for(int i=0;i<len;++i){
                    TreeNode *p=q.front();q.pop();
                    aaa.push_back(p->val);
                    if(p->left)  q.push(p->left);
                    if(p->right) q.push(p->right);  
                }
                all.push_back(aaa);
            }
            reverse(all.begin(), all.end());
            return all;
        }
    };
---------------------
作者:kirito0104
来源:CSDN
原文:https://blog.csdn.net/kirito0104/article/details/81939655
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-07-28 11:08  天涯海角路  阅读(110)  评论(0)    收藏  举报