Alex Rivera | Logout

Non-recursive depth first search algorithm

Asked 2011-03-11T21:29:40.777
220

I am looking for a non-recursive depth first search algorithm for a non-binary tree. Any help is very much appreciated.

Edit
Report

1 Answer

39

If you have pointers to parent nodes, you can do it without additional memory.

def dfs(root):
    node = root
    while True:
        visit(node)
        if node.first_child:
            node = node.first_child      # walk down
        else:
            while not node.next_sibling:
                if node is root:
                    return
                node = node.parent       # walk up ...
            node = node.next_sibling     # ... and right

Note that if the child nodes are stored as an array rather than through sibling pointers, the next sibling can be found as:

def next_sibling(node):
    try:
        i =    node.parent.child_nodes.index(node)
        return node.parent.child_nodes[i+1]
    except (IndexError, AttributeError):
        return None
answered 2011-03-12T20:53:06.350

Your Answer