zoukankan      html  css  js  c++  java
  • [LeetCode] Binary Tree Level Order Traversal

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

    For example: Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its level order traversal as:

    [
      [3],
      [9,20],
      [15,7]
    ]
    
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        queue<TreeNode*> q; //存放当前层的结点
        
        vector<vector<int> >res;//存放最终的结果
    
        vector<vector<int> > levelOrder(TreeNode *root) {
            
            if(root==NULL)
                return this->res;
            TreeNode *p = root;
            q.push(p);
            
            fun();
            return res;
        }
    private:
        void fun()
        {
            if(this->q.empty())
                return;
            TreeNode *pte;
            queue<TreeNode*> qnext;//存放下一层的结点
            vector<int> te;
            while(!this->q.empty() )
            {
                   pte = this->q.front();
                   this->q.pop();
                   te.push_back(pte->val);
                   if(pte->left!=NULL)
                   {
                       qnext.push(pte->left);
                   }
                   if(pte->right != NULL)
                   {
                       qnext.push(pte->right);
                   }
            }
            res.push_back(te);
            this->q = qnext;
            fun();    
        }
    };

    思路:用queue存放本层所有的结点,把本层处理完清空queue再存放下一层所有的结点。

  • 相关阅读:
    关于MYSQL 和INNODB的逻辑关系图。最好的理解是一点点动手做,观察,记录,思考。
    MYSQL的DOUBLE WRITE双写
    MYSQL 中binlog 参数的记录
    How to install pip
    gdb
    vim的基本使用
    012_fieldset.html
    010_header.html
    011_label.html
    008_img.html
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3869732.html
Copyright © 2011-2022 走看看