I have a tree with nodes that implement this interface
Interface Node { public boolean hasChildren() {}; } How can I return a List of List with same treeLevel ? for example if I have a tree like 1 2 开发者_如何学Go 3 4 5 6 7 I'll return a list of list like this {{1}{2,3}{4,5,6,7}} Thanks.This is basically a breadth-first traversal, except at each level you keep a list of that level. something like this example C# code:
IEnumerable<Node[]> Traverse(Node root) {
Node[] currentLevel = new [] { root };
Node[] nextLevel = null;
while(true) {
nextLevel = currentLevel.SelectMany(n => n.Children).ToArray();
if (nextLevel.Length > 0) {
yield return nextLevel;
currentLevel = nextLevel;
}
else {
break;
}
}
}
精彩评论