Skip to content

Commit ad9f68e

Browse files
committed
Visaul Studio: Add LevelOrder method for binary tree traversal
Implement a new static partial class `Solution` with a `LevelOrder` method that performs level order traversal of a binary tree. The method returns a list of lists containing node values at each level, utilizing a queue for traversal and handling null nodes effectively.
1 parent 08e3d37 commit ad9f68e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
using static LeetCodeNote.Solution;
7+
8+
public static partial class Solution
9+
{
10+
public static IList<IList<int>> LevelOrder(TreeNode root)
11+
{
12+
IList<IList<int>> result = new List<IList<int>>();
13+
if (root == null) return result;
14+
Queue<TreeNode> queue = new Queue<TreeNode>();
15+
queue.Enqueue(root);
16+
17+
while (queue.Count > 0)
18+
{
19+
int size = queue.Count;
20+
List<int> level = new List<int>();
21+
22+
for (int i = 0; i < size; i++)
23+
{
24+
TreeNode node = queue.Dequeue();
25+
level.Add(node.val);
26+
27+
if (node.left != null) queue.Enqueue(node.left);
28+
if (node.right != null) queue.Enqueue(node.right);
29+
}
30+
31+
result.Add(level);
32+
}
33+
34+
return result;
35+
}
36+
}

0 commit comments

Comments
 (0)