-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathLevelTraversalTree.cs
48 lines (47 loc) · 1.51 KB
/
LevelTraversalTree.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Tree.TreeLib
{
public class LevelTraversalTree
{
public IList<IList<int>> LevelOrder(TreeNode root)
{
if (root == null)
return new List<IList<int>>();
IList<IList<int>> rtn = new List<IList<int>> { new List<int> { root.val } };
var tmp = getNextLevel(new List<TreeNode> { root });
if (tmp != null && tmp.Count > 0)
{
foreach (var item in tmp)
rtn.Add(item);
}
return rtn;
}
private IList<IList<int>> getNextLevel(IList<TreeNode> curLevel)
{
if (curLevel == null || curLevel.Count == 0)
return null;
IList<IList<int>> rtn = new List<IList<int>>();
List<TreeNode> nextn = new List<TreeNode>();
foreach (var item in curLevel)
{
if (item.left != null)
nextn.Add(item.left);
if (item.right != null)
nextn.Add(item.right);
}
if (nextn.Count == 0)
return null;
rtn.Add(nextn.Select(r => r.val).ToList());
var children = getNextLevel(nextn);
if (children != null && children.Count > 0)
{
foreach (var item in children)
rtn.Add(item);
}
return rtn;
}
}
}