gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:21:26 27 4
gpt4 key购买 nike

有人可以教我如何使用 Proorder 和 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但没有效果。

最佳答案

这是一个 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;
}

关于javascript - 使用 PreOrder 和 InOrder 恢复二叉树 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45403346/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com