zoukankan      html  css  js  c++  java
  • 二叉树层次遍历

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

    样例

    给一棵二叉树 {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保存下来。

  • 相关阅读:
    C# 对XML操作-实例
    XML
    得到一个随机数组的方法
    Node Redis 小试
    Hexo快速搭建静态博客并实现远程VPS自动部署
    substr.js 字符串切割
    GraphicsMagick 学习笔记
    store.js 跨浏览器的localStorage
    bodyParser中间件的研究
    Sublime Text 使用指南
  • 原文地址:https://www.cnblogs.com/dynas/p/6993818.html
Copyright © 2011-2022 走看看