Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
06d96d1
commit 42b1dab
Showing
2 changed files
with
83 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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>> {}); | ||
} | ||
|
||
} | ||
} |