【发布时间】:2013-03-26 19:51:41
【问题描述】:
我试图熟悉在给定中序和后序遍历的情况下创建树的问题。我编写了以下代码,但有些事情出了问题,我无法找出。有人可以帮我解决这个问题吗?
样本 i/p:
int in[] = {4,10,3,1,7,11,8,2}; int post[] = {4,1,3,10,11,8,2,7};
public static TreeNode buildInorderPostorder( int post[], int n, int offset,Map<Integer,Integer> indexMap,int size) {
if (size <= 0) return null;
int rootVal = post[n-1];
int i = (indexMap.get(rootVal) - offset);
TreeNode root = new TreeNode(rootVal);
root.setLeft(buildInorderPostorder( post, i, offset,indexMap,i-offset));
root.setRight(buildInorderPostorder(post, n-1, offset+i,indexMap,n-1-i));
return root;
}
【问题讨论】:
-
中序遍历不应该有序吗?
-
它不是二叉搜索树
-
_______7______ / \ 10 ___2 / \ / 4 3 _8 \ / 1 11
标签: algorithm tree binary-tree tree-traversal inorder