0

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.

  • 3
    Note that you can draw many different binary trees with that post-order traversal... or did you mean a binary **search** tree? Can you show us your attempt at drawing such a tree? – Bernhard Barker Jun 10 '14 at 06:57
  • @Dukeling Could you show one for example? And please give brief explanation for steps if you don't mind for me to understand. Thank you! – user3724903 Jun 10 '14 at 07:13
  • 1
    Not identical, but this might help - [Can we construct a full binary tree with only postorder traversal or preorder traversal?](http://stackoverflow.com/q/23112589) – Bernhard Barker Jun 10 '14 at 07:15
  • @Dukeling I don't mean a binary search tree. It would help a lot if you can show me one of those many different binary trees with the given post-order traversal. – user3724903 Jun 10 '14 at 07:19

2 Answers2

1

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

Community
  • 1
  • 1
Vikram Bhat
  • 6,106
  • 3
  • 20
  • 19
0

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.

Jon Cage
  • 36,366
  • 38
  • 137
  • 215
htzfun
  • 1,231
  • 10
  • 41