• 二叉树层次遍历


    给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)

    样例

    给一棵二叉树 {3,9,20,#,#,15,7} :

      3
     / 
    9  20
      /  
     15   7
    

    返回他的分层遍历结果:

    [
      [3],
      [9,20],
      [15,7]
    ]
    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
     
     
    class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: Level order a list of lists of integer
         */
    public:
        vector<vector<int>> levelOrder(TreeNode *root) {
            // write your code here
            queue<TreeNode* > q;
            vector<vector<int > > result;
            if(root == NULL)return result;
            q.push(root);
            int count1 = 1,count2 = 0;
            vector<int > sur;
            while(!q.empty() )
            {
                
                TreeNode *tmp = q.front();
                q.pop();
                sur.push_back(tmp->val);
                count1--;
                if(tmp->left != NULL)
                {
                    q.push(tmp->left);
                    count2++;
                }
                if(tmp->right != NULL)
                {
                    q.push(tmp->right);
                    count2++;
                }
                if(count1 == 0)
                {
                    count1 = count2;
                    count2 = 0;
                    result.push_back(sur);
                    sur.clear();
                }
            }
            return result;
        }
    };

    count1保存当前层次的节点数,count2保存下一层的节点数,每出队列一个节点当前层节点数减一直到为零,count1与count2互换,并将vector保存下来。

  • 相关阅读:
    Linux软件安装中RPM与YUM 区别和联系(转载)
    linux文件系统
    (转载) linux基础知识
    linux学习:硬盘挂载
    IDEA版github教程(转载)
    idea配置gitee(转载)
    事与人的关系
    maven打包失败与问题反思
    计算机开机
    maven到底干了啥
  • 原文地址:https://www.cnblogs.com/dynas/p/6993818.html
Copyright © 2020-2023  润新知