我试图熟悉在给定中序和后序遍历的情况下创建树的问题。我编写了以下代码,但有些事情出了问题,我无法找出。有人可以帮我吗?
样本 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;
}