使用PreOrder和InOrder恢复二叉树 - Javascript

时间:2017-07-30 18:37:07

标签: javascript binary-tree inorder preorder

有人可以教我如何使用Prorder和Inorder数组恢复二叉树。我已经看过一些例子(在JavaScript中没有)并且它们有意义,但是当我尝试写时,递归调用永远不会返回完整的树。我也很乐意看到解释。这里有一些代码可以开始:

创建树节点使用:

function Tree(x) { 
  this.value = x;
  this.left = null;
  this.right = null;
}

创建树使用:

function retoreBinaryTree(inorder, preorder) {

}

一些示例输入:

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编写的)。我试图模仿this solution,但无济于事。

1 个答案:

答案 0 :(得分:0)

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

/* 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;
}