Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Tree traversal without recursion: the tree as a state machine

by pKai (Priest)
on Feb 16, 2007 at 22:54 UTC ( #600538=note: print w/replies, xml ) Need Help??

in reply to Tree traversal without recursion: the tree as a state machine

It's no coincidence that stacks have a close relationship with trees.

You can get rid of any stacks whatsoever by keeping a parent pointer in the tree node data structure.

I wouldn't say you "get rid of any stacks" here.

While you don't implement the stack as a list in classical ways, the list of "parent pointer(s)" between the root and the current node at any given moment of the traversal forms a stack.

While traversing, you need no memory other than the current and the previous node/state.

"previous node/state" obviously refers to the "top of stack", the single point where a stack is accessible.

  • Comment on Re: Tree traversal without recursion: the tree as a state machine

Replies are listed 'Best First'.
Re^2: Tree traversal without recursion: the tree as a state machine
by Aristotle (Chancellor) on Feb 16, 2007 at 23:41 UTC

    Yes, itís just a different form of storage of the same data. Obviously, you have to store enough information to find your way around the tree somewhere. If itís not one place, itís another. However, this algorithm really does not use a stack, at least not if you define a stack in the only way which makes sense Ė that is, as a data structure whose defining property is support for the operations of pushing things onto the top and popping them off the top.

    It consumes more space, of course, to keep all those parent pointers around. If you use a stack, they are transient and you only need O(log n) stack space, whereas itís O(n) if you store the pointers with the nodes Ė another way in which the two approaches are truly distinct.

    What I like about this approach (which is what compelled me to post it) is the exceptional simplicity of the traversal algorithm. When it first occured to me, it seemed too simple to work Ė but no, the position and direction of the traverser encodes enough information to guide its path along the entire tree in the right order without any ambiguity.

    Makeshifts last the longest.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://600538]
[Corion]: Oh. I've run out of prewritten articles. I need to release some more modules and write some more articles then ;)

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2017-04-24 08:47 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (437 votes). Check out past polls.