Traversing a n-ary tree without using recurrsion

前端 未结 3 1142
孤独总比滥情好
孤独总比滥情好 2020-12-08 05:21

How can I traverse an n-ary tree without using recursion?

Recursive way:

traverse(Node node)
{
    if(node == null)
        return;

            


        
3条回答
  •  半阙折子戏
    2020-12-08 05:43

    No language given, so in pseudo-pseudocode:

    traverse(Node node)
    {
      List nodes = [node];
    
      while (nodes.notEmpty) {
        Node n = nodes.shift();
    
        for (Node child in n.getChildren()) {
          nodes.add(child);
        }
    
        // do stuff with n, maybe
      }
    }
    

    Note that this is a breadth-first traversal as opposed to the depth-first traversal given in the question. You should be able to do a depth-first traversal by poping the last item off the nodes list instead of shifting the first one.

提交回复
热议问题