GeeksforGeeks » Trees specific questions
Traversal of binary search trees
(4 posts)-
I came across this problem about In-order Traversal of binary search tree without using a stack or recursion. Hint says to assume that testing of pointers for equality is a legitimate operation.I'm stuck finding the solution to this problem. Please give me some direction. I'm not looking for the code. Just give me the right direction.
-
Following is one solution that doesn't use recursion and stack.
1) Do level order traversal (or BFS) using Queue and store the elements in an array.
2) Sort the array and you get the Inorder traversal. -
The following is a more relevant solution to this problem. It assumes that you are storing the pointer to the parent of the node along with the pointers to left and the right children.
We store the node being currently examined in a pointer called the
curr
.
We store the node that was last examined in a pointer called the
prev
.curr --> holds the pointer to the node presently being examined; prev --> holds the pointer to the node that was last examined; prev=null; curr=root; while(curr!=null){ if(prev==curr.parent){ if(curr.left!=null){ prev=curr; curr=curr.left; } else{ process(curr); prev=curr; if(curr.right!=null) curr=curr.right; else curr=curr.parent; } } if(curr.left==prev){ process(curr); prev=curr; if(curr.right!=null){ curr=curr.right; } else curr=curr.parent; } if(curr.right==prev){ process(curr); prev=curr; curr=curr.parent; } } }Please go through it and point out errors if you find one .
-
Please remove the above comments.
Here is a url to the solution i think might be correct. Do discuss.
http://codepad.org/61KQNYKy
Reply
You must log in to post.