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,null,null,15,7],

    3
/ \
9 20
/ \
15 7

return its level order traversal as:

[
[3],
[9,20],
[15,7]
]

方案1,直接暴力枚举

Runtime: 280 ms, faster than 53.25% of C# online submissions for Binary Tree Level Order Traversal.
Memory Usage: 29.7 MB, less than 5.66% of C# online submissions for Binary Tree Level Order Traversal.
public class Solution {
private readonly List<Tuple<int, int>> _list = new List<Tuple<int, int>>(); private int _maxDepth; public IList<IList<int>> LevelOrder(TreeNode root)
{
IList<IList<int>> result = new List<IList<int>>();
GetAllNodes(root, );
for (int i = ; i <= _maxDepth; i++)
{
var temp = _list.Where(x => x.Item1 == i).Select(y => y.Item2).ToList();
result.Add(temp);
} return result;
} private void GetAllNodes(TreeNode node, int depth)
{
if (node == null)
return;
depth++;
if (_maxDepth < depth)
{
_maxDepth = depth;
}
_list.Add(new Tuple<int, int>(depth, node.val));
GetAllNodes(node.left, depth);
GetAllNodes(node.right, depth);
} private void WriteTreeNode(TreeNode node)
{
if (node == null)
{
Console.WriteLine("node is null");
return;
}
Console.Write($"node is {node.val}");
if (node.left == null)
{
Console.Write(", node.left is null");
}
else
{
Console.Write($", node.left is {node.left.val}");
}
if (node.right == null)
{
Console.WriteLine(", node.right is null");
}
else
{
Console.WriteLine($", node.right is {node.right.val}");
}
}
}

方案2,通过队列,在不同的depth中间插入null

https://stackoverflow.com/questions/31247634/how-to-keep-track-of-depth-in-breadth-first-search

You don't need to use extra queue or do any complicated calculation to achieve what you want to do. This idea is very simple.

This does not use any extra space other than queue used for BFS.

The idea I am going to use is to add null at the end of each level. So the number of nulls you encountered +1 is the depth you are at. (of course after termination it is just level).

 public IList<IList<int>> LevelOrder(TreeNode root)
{
Queue<TreeNode> queue = new Queue<TreeNode>(); IList<int> list = new List<int>();
IList<IList<int>> result = new List<IList<int>>(); if (root != null)
{
result.Add(list);
queue.Enqueue(root);
queue.Enqueue(null);
} while (queue.Count > )
{
var node = queue.Dequeue(); if (node == null)
{
queue.Enqueue(null);
if (queue.Peek() == null)
{
//You are encountering two consecutive `nulls` means, you visited all the nodes.
break;
}
else
{
list = new List<int>();
result.Add(list);
continue;
}
}
else
{
list.Add(node.val);
} Enqueue(queue, node.left);
Enqueue(queue, node.right);
} return result;
} private void Enqueue(Queue<TreeNode> tempQueue, TreeNode node)
{
if (node != null)
{
tempQueue.Enqueue(node);
}
}

这个的执行结果:

Runtime: 252 ms, faster than 86.41% of C# online submissions for Binary Tree Level Order Traversal.
Memory Usage: 29.1 MB, less than 87.74% of C# online submissions forBinary Tree Level Order Traversal.

举例

队列情况如下

(初始状态)

1 null1

(1出队列,1的左右子结点进队列)

null1  2  3

(null1出队列,说明depth=1遍历结束。新的null2进队列,depth=2结束的标志位,同时continue)

2   3 null2

(2出队列,2的左右子结点进队列)

3  null2  4  5

(3出队列,3的左右子结点入队列,因为3没有子结点,所以没有新进入queue的结点)

null2 4  5

(null2出队列,说明depth=2遍历结束。null3进队列,标记着depth=3结束的标志位,同时continue)

4  5 null3

(4出队列,4的左右子结点入队列,因为4没有子结点,所有没有新进入queue的结点)

5 null3

(5出队列,5的左右子结点入队列,因为5没有子结点,所有没有新进入queue的结点)

null3

(null3出队列,说明depth=3的遍历结束。null4进队列,标记着depth=4结束的标志位。这个时候queue.peek()=null4,连续2个null,意味着遍历结束,直接跳出循环)

102. Binary Tree Level Order Traversal 广度优先遍历的更多相关文章

  1. 102. Binary Tree Level Order Traversal ------层序遍历

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

  2. [LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历

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

  3. LeetCode之Binary Tree Level Order Traversal 层序遍历二叉树

    Binary Tree Level Order Traversal 题目描述: Given a binary tree, return the level order traversal of its ...

  4. 【LeetCode】102. Binary Tree Level Order Traversal (2 solutions)

    Binary Tree Level Order Traversal Given a binary tree, return the level order traversal of its nodes ...

  5. [刷题] 102 Binary Tree Level Order Traversal

    要求 对二叉树进行层序遍历 实现 返回结果为双重向量,对应树的每层元素 队列的每个元素是一个pair对,存树节点和其所在的层信息 1 Definition for a binary tree node ...

  6. Leetcode 102. Binary Tree Level Order Traversal(二叉树的层序遍历)

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

  7. LeetCode 102. Binary Tree Level Order Traversal 二叉树的层次遍历 C++

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

  8. 【LeetCode】102. Binary Tree Level Order Traversal 二叉树的层序遍历 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS DFS 日期 题目地址:https://lee ...

  9. leetcode 102. Binary Tree Level Order Traversal

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

随机推荐

  1. Unity shader学习之遮罩纹理

    什么是遮罩? 遮罩允许我们可以保护某些区域,使它们奂于某些修改. 例如下面的例子,使用遮罩来控制高光反射. 转载请注明出处:http://www.cnblogs.com/jietian331/p/71 ...

  2. WEB应用程序:AJAX全套

    概述 对于WEB应用程序:用户浏览器发送请求,服务器接收并处理请求,然后返回结果,往往返回就是字符串(HTML),浏览器将字符串(HTML)渲染并显示浏览器上. 1.传统的Web应用 一个简单操作需要 ...

  3. maven项目没有src/test/java和src/test/resources目录问题解决

    新建maven项目,如下图示: 只有src/main/java和src/main/resources两个目录,而没有src/test/java和src/test/resources,于是第一反应是没有 ...

  4. 51Nod 2020 排序相减

    题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=2020 思路:排序 水水 #include<iostre ...

  5. C#中对Web.Config、App.Config字符串加密与解密的方法

    我们平常的项目里面的配置文件通常都是明文形式的存在,现在就是为了项目安全性增强,同时又显得高逼格点, 我们可以采用加密的方式,而我们C#很强大,因为他内置的一些指令方式,很方便而且使用起来还不用解密, ...

  6. iOS项目之报错笔记

    问题一: linker command failed with exit code 1 (use -vto see invocation) 原因:导入了.m的头文件,导致同时有两个一样的.m文件在编译 ...

  7. 计算概论(A)/基础编程练习(数据成分)/3:整数的个数

    #include<stdio.h> int main() { ] = {}; // 输入k个正整数 scanf("%d",&k); // 循环读入和进行算术 w ...

  8. Let's Chat ZOJ - 3961

    ACM (ACMers' Chatting Messenger) is a famous instant messaging software developed by Marjar Technolo ...

  9. OpenGL: 实现立体显示

    https://blog.csdn.net/augusdi/article/details/19922295 立体显示原理:设没有立体显示的模型视图矩阵ModelView为Mv,投影矩阵为Mp,则.物 ...

  10. Scrapy小技巧-MySQL存储, MYSQL拼接

    这两天上班接手,别人留下来的爬虫发现一个很好玩的 SQL脚本拼接. 只要你的Scrapy Field字段名字和 数据库字段的名字 一样.那么恭喜你你就可以拷贝这段SQL拼接脚本.进行MySQL入库处理 ...