Binary Tree from inorder and postorder

一曲冷凌霜 提交于 2019-12-06 13:49:27

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

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

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