开发者

How to return tree within same level efficiently

开发者 https://www.devze.com 2023-04-09 03:50 出处:网络
I have a tree with nodes that implement this interface Interface Node { public boolean hasChildren() {};

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;
          }
      }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号