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保存下来。

  • 相关阅读:
    几种排序方法详解(选择排序、冒泡排序、插入排序、快速排序)
    几种排序方法详解(选择排序、冒泡排序、插入排序、快速排序)
    Cookie
    ajax
    layer弹出框
    Session
    Cookie
    顺时针打印矩阵
    常用判断
    基础学习
  • 原文地址:https://www.cnblogs.com/dynas/p/6993818.html
Copyright © 2011-2022 走看看