6

I can traverse the binary search tree using recursion easily, but I don't have an idea about traverse without recursion so please anyone explain,.....

2
  • 1
    have you tried anything yourself at first. please post the codes where you are stuck. Commented Oct 8, 2015 at 17:40
  • 1
    You should probably read Wikipedia page on Tree Traversal there are multiple algorithms there on how to do it with and without recursion. Commented Nov 22, 2021 at 17:07

1 Answer 1

5

yes, you can do it with stack. you have to take stack here the algorithm for p reorder, in-order and post-order traversal in iterative way (non recursive way/method) of binary search tree. Hope you will get properly.

p re order:

1) Create an empty stack node_Stack and push root node to stack.

2) Do following while node_Stack is not empty.

-> Pop an item from stack and print it.

-> Push right child of popped item to stack

-> Push left child of popped item to stack

in-order:

1) Create an empty stack S.

2) Initialize current node as root

3) Push the current node to S and set current = current->left until current is NULL

4) If current is NULL and stack is not empty then

 -> Pop the top item from stack.

 -> Print the popped item, set current = popped_item->right 

 -> Go to step 3.

5) If current is NULL and stack is empty then we are done.

post-order:

1.1 Create an empty stack

2.1 Do following while root is not NULL

-> Push root's right child and then root to stack.

-> Set root as root's left child.

2.2 Pop an item from stack and set it as root.

-> If the popped item has a right child and the right child 
   is at top of stack, then remove the right child from stack,
   push the root back and set root as root's right child.

-> Else print root's data and set root as NULL.

2.3 Repeat steps 2.1 and 2.2 while stack is not empty.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.