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;
    };
  • 相关阅读:
    近来感受
    GIT相关命令
    CMMI评审总结
    Windows下Git Bash的设置
    PHP学习三--常用运算符和结构语句
    PHP学习二--常量
    MYSQL基础十一--存储引擎
    MYSQL基础十--存储过程
    MYSQL基础九--自定义函数
    MYSQL基础八--子查询和连接
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854551.html
Copyright © 2011-2022 走看看