从inorder和post order遍历创建二叉树

时间:2013-03-26 19:51:41

标签: algorithm tree binary-tree tree-traversal inorder

我试图通过在顺序和后序遍历中创建树的问题进行熟悉。我写了下面的代码,但有些事情是错的,我无法找到。有人可以帮我吗?

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

1 个答案:

答案 0 :(得分:0)

root.setRight似乎有误。偏移不应该是offset+i,应该是offset+i+1

root.setRight(buildInorderPostorder(post, n-1, offset+i+1,indexMap,n-1-i));