Could someone show a drawing of a Binary Tree whose Post Order Iteration is: 12, 6, 2, 21, 27, 42, 9?
I am confused as to how to complete.
Could someone show a drawing of a Binary Tree whose Post Order Iteration is: 12, 6, 2, 21, 27, 42, 9?
I am confused as to how to complete.
For a general binary tree there are many trees that have same postorders but if you are mentioning a BST(Binary search tree) then you know that inorder is ascending order of keys so then you can use :- How to construct BST given post-order traversal
Let's go through the definition of post order traversal:
it means that root will be printed in the end. As has been mentioned above - many trees got the postorder code, but the only one BST tree got the same postorder code.
So how to build tree? Let's write recursive algorithm:
1) You got sequence of numbers, where the last one is the root. So put it into root! At first iteration this is 9.
9
/ \
2) After this find the first number bigger than root, starting from the beginning. At first iteration this is 21. 3) Split your sequence of numbers into two parts on found number:
[12,6,2,21,27,42] -> [12,6,2] and [21,27,42]
4) Solve the problem for this two sequences. The tree built from first sequence will be left part of tree, the second - the right one.
That's it. The result of this algorithm for this case will be:
9
/ \
/ \
/ \
2 42
\ /
6 27
\ /
12 21
Sorry, for weird picture.