https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/
/// </summary>
[TestClass]
public class ZigzagLevelOrderTest
{
[TestMethod]
public void TestZigZag()
{
/* 3
/ \
9 20
/ \
15 7
*/
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
IList<IList<int>> res = ZigzagLevelOrderClass.ZigzagLevelOrder(root);
CollectionAssert.AreEqual(new List<int> { 3 }, res[0].ToList());
CollectionAssert.AreEqual(new List<int> { 20, 9 }, res[1].ToList());
CollectionAssert.AreEqual(new List<int> { 15, 7 }, res[2].ToList());
}
[TestMethod]
public void FailedTest()
{
/* 1
/ \
2 3
/ \
4 5
*/
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.right.right = new TreeNode(5);
IList<IList<int>> res = ZigzagLevelOrderClass.ZigzagLevelOrder(root);
CollectionAssert.AreEqual(new List<int> { 1 }, res[0].ToList());
CollectionAssert.AreEqual(new List<int> { 3, 2 }, res[1].ToList());
CollectionAssert.AreEqual(new List<int> { 4, 5 }, res[2].ToList());
}
}
public class ZigzagLevelOrderClass
{
public static IList<IList<int>> ZigzagLevelOrder(TreeNode root)
{
List<IList<int>> result = new List<IList<int>>();
if (root == null)
{
return result;
}
Stack<TreeNode> currentLeveL = new Stack<TreeNode>();
Stack<TreeNode> nextLevel = new Stack<TreeNode>();
currentLeveL.Push(root);
while (currentLeveL.Count > 0 || nextLevel.Count > 0)
{
var nodes = new List<int>();
while (currentLeveL.Count > 0)
{
var curr = currentLeveL.Pop();
if (curr.left != null)
{
nextLevel.Push(curr.left);
}
if (curr.right != null)
{
nextLevel.Push(curr.right);
}
nodes.Add(curr.val);
}
if (nodes.Count > 0)
{
result.Add(nodes);
}
nodes = new List<int>();
while (nextLevel.Count > 0)
{
var curr = nextLevel.Pop();
if (curr.right != null)
{
currentLeveL.Push(curr.right);
}
if (curr.left != null)
{
currentLeveL.Push(curr.left);
}
nodes.Add(curr.val);
}
if (nodes.Count > 0)
{
result.Add(nodes);
}
}
return result;
}
}
Please review for performance. this is the second time I solved this question. I think I did a better job now.