Sword finger offer|rebuild binary tree

Title: input the results of the preorder traversal and inorder traversal of a binary tree, please reconstruct the binary tree. It is assumed that the number in the result of the input preorder traversal and inorder traversal is not repeated. If the sequence {1, 2, 4, 7, 3, 5, 6, 8} and the sequence {4, 7, 2, 1, 5, 3, 8, 6} are input, the binary tree as shown in the figure will be reconstructed

For the idea of reconstructing binary tree:
The root node of the binary tree can be obtained according to the sequence of preorder, and then the root node can be found in the middle order traversal, so the binary tree is divided into two parts, the left subtree and the right subtree on the left and right, and then the left and right subtrees are carried out in the previous steps: each time, the start address and end address of the front and middle order traversal of the left and right subtrees are calculated.

The code is as follows:

Code:

//Reconstruction of binary tree based on preorder sequence and mesophase sequence
BTNode* Construct(int* Prevstart, int* Prevend, int* Instart, int* Inend)
{
    assert(Prevend && Prevstart && Instart && Inend);

    //Create root node
    BTNode* root = BuyBTNode(*Prevstart);

    //Determine whether the binary tree has only one root node
    if (Prevend - Prevstart == 0)
    {
        if (Inend - Instart == 0 && *Prevstart == *Instart)
        {
            return root;
        }
        else
        {
            printf("Please check whether the input is correct 1!\n");
            exit(1);
        }
    }

    //The binary tree has more than one node
    //In the middle order sequence, find the root node, divide it into two parts, and reconstruct it recursively
    int* InOrderRoot = Instart;
    while (*InOrderRoot != *Prevstart && InOrderRoot < Inend)
    {
        InOrderRoot++;
    }

    //Root node not found in middle order traversal
    if (InOrderRoot == Inend && *InOrderRoot != *Prevstart)
    {
        printf("Please check whether the input is correct 2!\n");
        exit(1);
    }

    //Length of left subtree
    int length_left = InOrderRoot - Instart;
    //Reconstruction of left subtree
    if (length_left > 0)
    {
        root->_left = Construct(Prevstart + 1, Prevstart + length_left, Instart, InOrderRoot - 1);
    }

    //Reconstruction of right subtree
    if (length_left < Prevend - Prevstart)
    {
        root->_right = Construct(Prevstart + length_left + 1, Prevend, InOrderRoot + 1, Inend);
    }
    return root;
}

Posted by smpdawg on Fri, 03 Jan 2020 00:49:42 -0800