美文网首页二叉树之下
二叉树的层次遍历

二叉树的层次遍历

作者: 杰米 | 来源:发表于2016-09-05 11:24 被阅读903次

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
给一棵二叉树 {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) {
         vector<vector<int>>result;
        if (root == NULL) {
            return  result;
        }
        // write your code here
       
        deque<TreeNode *>oneQueue;
        TreeNode *head = root;
        oneQueue.push_back(head);
        int currentLevel = 0;
        int currentLevelInternalCount = 1;
        int nextLevelInternalCount = 0;
        int count = 0;
        vector<int>levelNums;
        while(!oneQueue.empty()) {
            head = oneQueue.front();
            oneQueue.pop_front();
            count++;
           levelNums.push_back(head->val);
            if (head->left != NULL) {
                oneQueue.push_back(head->left);
                nextLevelInternalCount++;
            }
            if(head->right != NULL) {
                oneQueue.push_back(head->right);
                nextLevelInternalCount++;
            }
             if (count == currentLevelInternalCount) {
                vector<int> a = levelNums;
                //vector<int>a(2,0);
                result.push_back(a);
                levelNums.clear();
                count = 0;
                currentLevelInternalCount = nextLevelInternalCount;
                nextLevelInternalCount = 0;
            }
        }
        return result;
    }
};

相关文章

  • 二叉树的蛇形层次遍历(LeetCode.103)

    题目 解析 首先参考二叉树的层次遍历层次遍历二叉树(LeetCode--102二叉树的层次遍历)[https://...

  • 二叉树遍历

    二叉树遍历(非递归写法) 先序遍历 中序遍历 后序遍历 层次遍历 给定一个二叉树,返回其按层次遍历的节点值。 (即...

  • 二叉树的基本算法

    一、二叉树的递归遍历 二、二叉树的层次遍历 二叉树的层次遍历是指二叉树从上到下,从左到右遍历数据。同一层中的节点访...

  • 二叉树的层次遍历

    三道层次遍历题,同一个模板,这边用到的是两个队列 二叉树的层次遍历 LeetCode题目地址 二叉树的层次遍历 加...

  • 二叉树的层次遍历

    一、二叉树的层次遍历原理 如图所示为二叉树的层次遍历,即按照箭头所指方向,按照1、2、3、4的层次顺序,对二叉树中...

  • 二叉树 基础操作

    二叉树的使用 二叉树结构 先序创建二叉树 DFS 先序遍历二叉树 中序遍历二叉树 后序遍历二叉树 BFS 层次遍历...

  • 数据结构重学日记(二十二)二叉树的层次遍历

    二叉树的层次遍历也属于非递归遍历,和之前先序、中序、后序遍历的区别在于层次遍历需要借助队列来实现。 层次遍历的操作...

  • 二叉树遍历

    1.层次遍历(广度优先遍历) 用队列实现,队首出队,队首的子节点入队。 1,二叉树的层次遍历, 打印 2,二叉树的...

  • 力扣题解(树)

    100. 相同的树 101. 对称二叉树 102. 二叉树的层次遍历 103. 二叉树的锯齿形层次遍历 104. ...

  • 二叉树的各种遍历方法

    二叉树的常用遍历方法 二叉树常用的遍历方法包括: 前序遍历 中序遍历 后序遍历 层次遍历 而前三种遍历的具体实现上...

网友评论

    本文标题:二叉树的层次遍历

    本文链接:https://www.haomeiwen.com/subject/oyjrettx.html