【问题标题】:Create binary tree from inorder and post order traversal从中序和后序遍历创建二叉树
【发布时间】: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


【解决方案1】:

root.setRight好像错了。offset不应该是offset+i,应该是offset+i+1

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

【讨论】:

  • 我试过了,但还是不行 .public static TreeNode buildInorderPostorder( int post[], int n, int offset,Map indexMap,int size) { if (size
  • 我正在检查进一步的错误。您能否将整个程序发布到 ideone ideone.com 并将链接发送给我们?
猜你喜欢
  • 2011-07-09
  • 1970-01-01
  • 2014-12-30
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 2021-09-03
相关资源
最近更新 更多