Reconstructing binary tree from inorder and preorder traversals

末鹿安然 提交于 2019-12-09 19:24:18

问题


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:


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?



来源:https://stackoverflow.com/questions/3253106/reconstructing-binary-tree-from-inorder-and-preorder-traversals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!