2
votes

I have just started studying Binary Tree. Is there an algorithm to find out the binary tree structure,given the Inorder and Postorder OR Inorder and Preorder? I have been trying to do it manually,but it never comes out correct.For eg.-These two are valid Inorder and Postorder traversal of a given tree:

Inorder: D B F E A G C L J H K Postorder : D F E B G L J K H C A

Clearly A is the root as it is the last element in Postorder. Now looking in Inorder,the left subtree becomes: {D B F E} and right subtree becomes: {G C L J H K}. The root of right subtree would be the second last element in preorder i.e C. I can now further divide the right subtree(with C as root), giving {G} as right subtree and {L J H K} as left. Therefore I have this structure:

                               A
                                \
                                 C
                                /  
                               G

But,whatever algorithm I apply,next seems to work differently for different trees . Someone please explain.

2
divide […subtree] with C as root), giving {G} as right subtree and {L J H K} as left - this has the "labels" left and right invertedgreybeard

2 Answers

1
votes

If I understand what your asking, your trying to reverse engineer the underlying structure for a given binary tree search algorithm given the raw data in it's pre and post state. If this is the case you could be down a difficult road since although the basic algorithm is the same, there could be nuances to it depending on the developer that build the algorithm since in practice it is often the case the developers do not build a pure implementation of these algorithms.

If your just trying to get a better understanding of binary trees, this may explain it a little better: http://www.youtube.com/watch?v=ZkH3SSPwcwI

0
votes

Let the inorder and preorder traversals be given in the arrays iorder and porder respectively.

The function to build the tree will be denoted by buildTree(i,j,k) where i,j refer to the range of the inorder array to be looked at and k is the position in the preorder array.

Initial call will be buildTree(0,n-1,0)

The algorithm has the following steps:

  1. Traverse porder from start. The first node is the root, then we have the left subtree and then the right subtree. Create a node with this as the element.

  2. Search the node in the iorder array. Suppose its found at x. Decrement k. k refers to the position in the porder array we are currently at. k has to be passed by reference.

  3. Finally populate the left child and right child with the return value of the recursive calls left child = buildTree(i,x-1,k) right child = buildTree(x+1,j,k)

  4. In the end return the node

PS: Got the code accepted with the above algorithm at

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=477