Can anyone give me a solution for traversing a binary tree in inorder without recursion and without using a stack?
views:
458answers:
3
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
2010-04-07 18:56:37
A threaded tree would seem to meet Gogu's requirements.
Jim Lewis
2010-04-07 19:01:32
+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
2010-04-07 19:01:36
I'm fairly certain this is going to have problems with trees of depth > 2.
Daniel Spiewak
2010-04-07 19:04:10
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
2010-04-07 19:04:54
If you have node.parent, you don't need node.isRoot. Also, I think you can do without node.isLeftChild.
Beta
2010-04-07 20:07:58
A:
Yes, you can. In order to do this, you would require a parent pointer in order to ascend the tree.
1337c0d3r
2010-10-28 22:43:14