Reconstructing binary tree from inorder and preord

2020-07-22 04:33发布

I have written the following code for constructing a tree from its inorder and preorder traversals. It looks correct to me but the final tree it results in does not have the same inorder output as the one it was built from. Can anyone help me find the flaw in this function?

public btree makeTree(int[] preorder, int[] inorder,  int left,int right)
{
    if(left > right)
        return null;

    if(preIndex >= preorder.length)
        return null;

    btree tree = new btree(preorder[preIndex]);
    preIndex++;

    int i=0;
    for(i=left; i<= right;i++)
    {
        if(inorder[i]==tree.value)
            break;

    }


        tree.left = makeTree(preorder, inorder,left, i-1);
        tree.right = makeTree(preorder, inorder,i+1, right );

    return tree;

}

Note: preIndex is a static declared outside the function.

1条回答
贪生不怕死
2楼-- · 2020-07-22 04:56
in = {1,3,2,5}; pre = {2,1,5,3};

I've some difficulties constructing the tree 'by hand'. pre shows that 2 must be the root, in shows that {1,3} are nodes of the left subtree, {5} is the right subtree:

      2
     / \
    /   \
  {1,3} {5}

But knowing this, 3 can't be the last element in pre because it is clearly an element of the left subtree and we have a right subtree. Valid preorder traversals for these trees are {2,1,3,5} or {2,3,1,5}. But {2,1,5,3} is impossible.

Maybe the bug is not in this method but in your algorithm to create inorder and preorder traversals. Or, could it be, that you chose the values for in[] and pre[] randomly?

查看更多
登录 后发表回答