Skip to content

Commit 2181b70

Browse files
committed
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
1 parent 3d50067 commit 2181b70

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
namespace LeetCodeSolutions.BinaryTreeBfs
2+
{
3+
class BinaryTreeZigzagLevelOrderTraversal
4+
{
5+
public IList<IList<int>> ZigzagLevelOrder(TreeNode root)
6+
{
7+
// Create a dictionary to store nodes at each level
8+
var levelMap = new Dictionary<int, IList<int>>();
9+
10+
// Perform a depth-first traversal to populate the level map
11+
TraverseBinaryTree(root, 0, levelMap);
12+
13+
// Convert the dictionary values to a list and return
14+
return levelMap.Values.ToList();
15+
}
16+
17+
private void TraverseBinaryTree(TreeNode node, int level, IDictionary<int, IList<int>> levelMap)
18+
{
19+
if (node == null) return;
20+
21+
// If this level hasn't been encountered before, add it to the dictionary
22+
if (!levelMap.ContainsKey(level))
23+
{
24+
levelMap[level] = new List<int>();
25+
}
26+
27+
// Add the node's value to the appropriate level
28+
// For even levels, add to the end; for odd levels, add to the beginning
29+
if (level % 2 == 0)
30+
{
31+
levelMap[level].Add(node.val);
32+
}
33+
else
34+
{
35+
levelMap[level].Insert(0, node.val);
36+
}
37+
38+
// Recursively traverse left and right children
39+
TraverseBinaryTree(node.left, level + 1, levelMap);
40+
TraverseBinaryTree(node.right, level + 1, levelMap);
41+
}
42+
43+
[Test(Description = "https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/")]
44+
[Category("Medium")]
45+
[Category("LeetCode")]
46+
[Category("Binary Tree Zig Zag Level Order Traversal")]
47+
[TestCaseSource(nameof(Input))]
48+
[Category("Binary Tree BFS")]
49+
[Category("TopInterview")]
50+
public void Test1((IList<IList<int>> Output, int?[] Input) item)
51+
{
52+
var response = this.ZigzagLevelOrder(item.Input.ToTreeNode());
53+
Assert.That(response, Is.EqualTo(item.Output));
54+
}
55+
56+
public static IEnumerable<(IList<IList<int>> Output, int?[] Input)> Input =>
57+
new List<(IList<IList<int>> Output, int?[] Input)>()
58+
{
59+
(new List<IList<int>>()
60+
{
61+
new List<int>() { 3 },
62+
new List<int>() { 20, 9 },
63+
new List<int>() { 15, 7 },
64+
}, [3, 9, 20, null, null, 15, 7])
65+
};
66+
}
67+
}

0 commit comments

Comments
 (0)