0
$\begingroup$

This question already has an answer here:

I have given a post order & in order traversal a BST & I need to construct it. I want to know how to do this.

for eg.

Post Order : DCBGFEA

In Order : BDCAFGE

This is how I am trying to do :

  • From POST order it is clear that A is root. So in IN order, I consider everything right to A is at it's right sub tree & so for left.

    image1

  • Now, I consider A's left sub tree. It has BDC. Again from POST order, I conclude that B is root.

    image2

  • Now, again consider B's sub tree. It has contents DC & POST order, C has to be at root. So now I get C at root. But where to place C, at B's left or right ? It's where I am getting stuck now.

Same happening with A's right sub tree also. I place E as root of A's right sub tree. Then I conclude element below should be F, but does it come at right or left of E ?

I want to know how to tackle this problem & also is there any better approach for this to do.

$\endgroup$

marked as duplicate by Raphael Apr 4 '13 at 12:05

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1
$\begingroup$

You are doing well. From the postorder determine the root, from the inorder determine which letters are in the left and right subtrees. Once you have done that, you can proceed in the same way for the subtrees.

In the example you start with postorder DCBGFE A and inorder BDC A FGE.

Using postorder you determine the root as A, and using inorder split the letters into left BDC and FGE. Thus (1) the left subtree has postorder DCB and inorder BDC while (2) the right subtree has postorder GFE and inorder FGE.

Let us look at left subtree (1) which you mention in your question. The root is B, and both DC follow to B in the inorder and thus are right from B. How to place them. This tiny subtree has postorder DC and inorder DC. Hence its root is C, and D is before C in the inorder, and is in the left subtree of C.

$\endgroup$
  • $\begingroup$ ^thank you ! I solved this question & verified, it seems correct - i.stack.imgur.com/4lU39.jpg $\endgroup$ – avi Apr 6 '13 at 15:36
  • $\begingroup$ You are welcome. A good trick indeed is to determine the traversals of the answer you obtain. They of course should match those from the question. $\endgroup$ – Hendrik Jan Apr 6 '13 at 22:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.