Skip to content

Commit

Permalink
ZigzagLevelOrder
Browse files Browse the repository at this point in the history
  • Loading branch information
hitochan777 committed Jul 25, 2020
1 parent 06d96d1 commit 42b1dab
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
53 changes: 53 additions & 0 deletions leetcode/csharp/src/ZigzagLevelOrder.cs
@@ -0,0 +1,53 @@
using System.Collections.Generic;
using System.Linq;

namespace ZigzagLevelOrder
{

public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
{
this.val = val;
this.left = left;
this.right = right;
}
}

public class Solution
{
public IList<IList<int>> ZigzagLevelOrder(TreeNode root)
{
if (root == null)
{
return new List<IList<int>>();
}
IList<IList<int>> list = new List<IList<int>>();
var q = new List<TreeNode> {root};
bool fromLeft = true;
var nextQ = new List<TreeNode>();
while (q.Count() > 0)
{
foreach (var node in q)
{
nextQ.Add(node.left);
nextQ.Add(node.right);
}
if (!fromLeft)
{
q.Reverse();
}
list.Add(new List<int>(q.Select(node => node.val)));
fromLeft = !fromLeft;
q = nextQ;
nextQ = new List<TreeNode>();
q.RemoveAll(node => node == null);
}
return list;
}
}

}
30 changes: 30 additions & 0 deletions leetcode/csharp/test/ZigzagLevelOrderTest.cs
@@ -0,0 +1,30 @@
using System.Collections.Generic;
using NUnit.Framework;

namespace ZigzagLevelOrder
{
public class Tests
{
[SetUp]
public void Setup()
{
}

[Test]
public void Test1()
{
var solver = new Solution();
var root = new TreeNode { val = 3, left = new TreeNode { val = 9 }, right = new TreeNode { val = 20, left = new TreeNode { val = 15 }, right = new TreeNode { val = 7 } } };
Assert.AreEqual(solver.ZigzagLevelOrder(root), new List<List<int>> { new List<int> { 3 }, new List<int> { 20, 9 }, new List<int> { 15, 7 } });
}

[Test]
public void Test2()
{
var solver = new Solution();
TreeNode root = null;
Assert.AreEqual(solver.ZigzagLevelOrder(root), new List<List<int>> {});
}

}
}

0 comments on commit 42b1dab

Please sign in to comment.