First element in the preorder[] will definitely be the root, which is 20 here.

Create a node with data 20 and push it in Stack.

Now take the next element (say ‘data’) from the preorder sequence.

If ‘data’ is greater than the top item in the stack then keep popping out the nodes from the stack, keep storing it in temp node till the top node in stack is less than the ‘data’.

create a node with ‘data’ and add it to the right of temp node and push the temp node to stack.

If ‘data’ is less than the top item in the stack then create a node with ‘data’ and add it to the left of top node in stack and push it in the stack.

Repeat the above two steps till all the elements in preorder[] is over.

return the root

Time Complexity: O(n)

Complete Code:

Output:

Inorder Traversal of Constructed Tree :
2 5 7 10 12 15 20

__________________________________________________ Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________