views:

458

answers:

3

Can anyone give me a solution for traversing a binary tree in inorder without recursion and without using a stack?

A: 

Since traversing a binary tree requires some kind of state (nodes to return after visiting successors) which could be provided by stack implied by recursion (or explicit by an array).

The answer is no, you can't. (according to the classic definition)

The closest thing to a binary tree traversal in an iterative way is probably using a heap

EDIT: Or as already shown a threaded binary tree ,

stacker
A threaded tree would seem to meet Gogu's requirements.
Jim Lewis
+3  A: 

Second edit: I think this is right. Requires node.isRoot, node.isLeftChild, and node.parent, in addition to the usual node.left_child and node.right_child.

state = "from_parent"
current_node = root
while (!done)
  switch (state)
    case "from_parent":
      if current_node.left_child.exists
        current_node = current_node.left_child
        state = "from_parent"
      else
        state = "return_from_left_child"
    case "return_from_left_child"
      if current_node.right_child.exists
        current_node = current_node.right_child
        state = "from_parent"
      else
        state = "return_from_right_child"
    case "return_from_right_child"
      if current_node.isRoot
        done = true
      else
        if current_node.isLeftChild
         state = "return_from_left_child"
        else
         state = "return_from_right_child"
        current_node = current_node.parent
mbeckish
I'm fairly certain this is going to have problems with trees of depth > 2.
Daniel Spiewak
You beat me to it. But note that this works only if the field node.parent exists, that is if the node knows its parent. This is permitted, but not required, by the definition of a binary tree.
Beta
If you have node.parent, you don't need node.isRoot. Also, I think you can do without node.isLeftChild.
Beta
@Danial: No this works just fine
lalitm
A: 

Yes, you can. In order to do this, you would require a parent pointer in order to ascend the tree.

1337c0d3r