Reconstructing a binary tree using order and order

I wrote the following code to build a tree from my order traversal orders and preorders. This looks right to me, but the last tree that results from it does not have the same inorder output as the one from which it was built. Can someone help me find a flaw in this feature?

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 declaration outside the function.

+3
source share
1 answer
in = {1,3,2,5}; pre = {2,1,5,3};

"". pre , 2 , in , {1,3} , {5} :

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

, 3 pre, . : {2,1,3,5} {2,3,1,5}. {2,1,5,3} .

, , . , , in[] pre[]?

+5

Source: https://habr.com/ru/post/1754756/


All Articles