首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用PreOrder和InOrder恢复二叉树

用PreOrder和InOrder恢复二叉树
EN

Stack Overflow用户
提问于 2017-07-30 18:37:07
回答 1查看 571关注 0票数 1

有人能教我如何用Prorder和无序数组恢复二叉树吗?我看到了一些示例(在JavaScript中没有),它们有点道理,但是当我尝试编写时,递归调用永远不会返回完整的树。也想看看解释。下面是一些开始的代码:

创建树节点使用如下:

代码语言:javascript
复制
function Tree(x) { 
  this.value = x;
  this.left = null;
  this.right = null;
}

创建树使用如下:

代码语言:javascript
复制
function retoreBinaryTree(inorder, preorder) {

}

一些样本输入:

代码语言:javascript
复制
inorder = [4,2,1,5,3]
preorder = [1,2,4,3,5,6]

inorder = [4,11,8,7,9,2,1,5,3,6]
preorder = [1,2,4,11,7,8,9,3,5,6]

编辑--我已经在这方面工作了好几天了,无法找到自己的解决方案,所以我搜索出了一些(大多数都是用Java编写的)。我试图模仿这个解决方案,但没有成功。

EN

回答 1

Stack Overflow用户

发布于 2017-07-30 22:49:48

这是C++中的一个解决方案,我认为您可以毫无问题地翻译它:

代码语言:javascript
复制
/* keys are between l_p and r_p in the preorder array

   keys are between l_i and r_i in the inorder array
 */
Node * build_tree(int preorder[], long l_p, long r_p,
          int inorder[], long l_i, long r_i)
{
  if (l_p > r_p)
    return nullptr; // arrays sections are empty

  Node * root = new Node(preorder[l_p]); // root is first key in preorder
  if (r_p == l_p)
    return root; // the array section has only a node

  // search in the inorder array the position of the root
  int i = 0;
  for (int j = l_i; j <= r_i; ++j)
    if (inorder[j] == preorder[l_p])
      {
        i = j - l_i;
        break;
      }

  root->left = build_tree(preorder, l_p + 1, l_p + i, 
              inorder, l_i, l_i + (i - 1));
  root->right = build_tree(preorder, l_p + i + 1, r_p, 
               inorder, l_i + i + 1, r_i);

  return root;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45403346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档