102. Binary Tree Level Order Traversal 广度优先遍历

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, 0);
            for (int i = 1; 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 > 0)
            {
                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,意味着遍历结束,直接跳出循环)

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(261)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2015-04-02 Top 10 steps to optimize data access in SQL Server
2015-04-02 How I explained OOD to my wife
点击右上角即可分享
微信分享提示