zoukankan      html  css  js  c++  java
  • 107. Binary Tree Level Order Traversal II(Tree, WFS)

    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]
    ]
    

    思路:使用两个队列完成层次搜索,结果存储在vector中。

    若使用一个队列,也可完成层次遍历,只是不清楚遍历到哪个层次了。两个队列可以知道目前元素所在的层次。

    /**
     * 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) {
            result.clear();
            if(!root) return result;
            
            vector<int> level;
            TreeNode * current;
            queue<TreeNode * > queToPop;
            queue<TreeNode * > queToPush;
            queToPop.push(root);
            while(!queToPop.empty())
            {
                while(!queToPop.empty())
                {
                    current = queToPop.front();
                    queToPop.pop();
                    level.push_back(current->val);
                    if(current->left)
                    {
                        queToPush.push(current->left); //若使用一个队列,这里应该是queToPop.push(...),只要queToPop不为空,就继续pop和push
                    }
                    if(current->right)
                    {
                        queToPush.push(current->right);
                    }
                }
               
                result.push_back(level);
                level.clear();
                swap(queToPop, queToPush);
            }
            
            reverse(result.begin(), result.end()); //逆序vector的方法
            return result;
        }
    private:
        vector<vector<int>> result;
    };
  • 相关阅读:
    react-native window下创建Hello(解决创建一路的坑)
    vue2.0 监听滚动 锚点定位
    vue-awesome-swiper 轮播图使用
    vue和react区别
    vuex 管理状态
    vue 解决axios 跨域问题
    判断一个对象是否为空? js
    微信小程序中的自定义组件(components)
    深入理解ES6箭头函数中的this
    vue中组件的data为什么是一个函数
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854551.html
Copyright © 2011-2022 走看看