有人能教我如何用Prorder和无序数组恢复二叉树吗?我看到了一些示例(在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编写的)。我试图模仿这个解决方案,但没有成功。
发布于 2017-07-30 22:49:48
这是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;
}https://stackoverflow.com/questions/45403346
复制相似问题