0

我试图熟悉在给定中序和后序遍历的情况下创建树的问题。我编写了以下代码,但有些事情出了问题,我无法找出。有人可以帮我吗?

样本 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;
    }
4

1 回答 1

0

root.setRight似乎是错误的。offset 不应该是offset+i,应该是offset+i+1

root.setRight(buildInorderPostorder(post, n-1, offset+i+1,indexMap,n-1-i));
于 2013-03-26T20:03:48.213 回答