Skip to content

Commit 3096907

Browse files
committed
Add symmetric tree check and zigzag traversal method
Implemented the `IsSymmetric` and `IsMirror` methods in `101.SymmetricTree.cs` to check for symmetry in binary trees. Removed unnecessary using directive in `102.BinaryTreeLevelOrderTraversal.cs`. Introduced `103.BinaryTreeZigzagLevelOrderTraversal.cs` with a new `ZigzagLevelOrder` method for zigzag level order traversal of binary trees.
1 parent ad9f68e commit 3096907

3 files changed

+75
-12
lines changed

101-110/101.Symmetric Tree.cs renamed to 101-110/101.SymmetricTree.cs

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,4 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Text;
5-
using System.Threading.Tasks;
6-
7-
8-
namespace LeetCodeNote;
1+
namespace LeetCodeNote;
92

103
public static partial class Solution
114
{
@@ -33,6 +26,4 @@ public static bool IsMirror(TreeNode root1, TreeNode root2)
3326
return (left && right);
3427

3528
}
36-
}
37-
38-
? true : false;
29+
}

101-110/102.BinaryTreeLevelOrderTraversal.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
using System.Linq;
44
using System.Text;
55
using System.Threading.Tasks;
6-
using static LeetCodeNote.Solution;
6+
namespace LeetCodeNote;
77

88
public static partial class Solution
99
{
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
using System.Collections.Generic;
2+
3+
namespace LeetCodeNote;
4+
5+
public static partial class Solution
6+
{
7+
public static IList<IList<int>> ZigzagLevelOrder(TreeNode root)
8+
{
9+
IList<IList<int>> result = new List<IList<int>>();
10+
if (root == null) return result;
11+
Stack<TreeNode> stack = new Stack<TreeNode>();
12+
stack.Push(root);
13+
int level = 0;
14+
15+
while (stack.Count > 0)
16+
{
17+
IList<int> currLevel = new List<int>();
18+
Queue<TreeNode> q = new Queue<TreeNode>();
19+
20+
while (stack.Count > 0)
21+
{
22+
q.Enqueue(stack.Pop());
23+
}
24+
25+
if (level % 2 == 0)
26+
{
27+
28+
while (q.Count > 0)
29+
{
30+
TreeNode temp = q.Dequeue();
31+
32+
if (temp.left != null)
33+
{
34+
stack.Push(temp.left);
35+
}
36+
37+
if (temp.right != null)
38+
{
39+
stack.Push(temp.right);
40+
}
41+
42+
currLevel.Add(temp.val);
43+
}
44+
}
45+
else
46+
{
47+
48+
while (q.Count > 0)
49+
{
50+
TreeNode temp = q.Dequeue();
51+
52+
if (temp.right != null)
53+
{
54+
stack.Push(temp.right);
55+
}
56+
57+
if (temp.left != null)
58+
{
59+
stack.Push(temp.left);
60+
}
61+
62+
currLevel.Add(temp.val);
63+
}
64+
}
65+
66+
result.Add(currLevel);
67+
level++;
68+
}
69+
70+
return result;
71+
}
72+
}

0 commit comments

Comments
 (0)