Binary Tree from inorder and postorder

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-14 01:41:22

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/12556682/binary-tree-from-inorder-and-postorder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!