105. Construct Binary Tree from Preorder and Inorder Traversal

时间:2022-05-01 12:39:24

Q

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

Given preorder and inorder traversal of a tree, construct the binary tree.

A

/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
    if (!preorderSize || !inorderSize || preorderSize != inorderSize) {
        return NULL;
    }

    struct TreeNode *p;
    p = (struct TreeNode *)malloc(sizeof(struct TreeNode));
    p->val = *preorder;

    int i = 0;
    while(*preorder != inorder[i])
        ++i;
    p->left = buildTree(preorder+1, i, inorder, i);
    p->right = buildTree(preorder+i+1, preorderSize-i-1, inorder+i+1, inorderSize-i-1);

    return p;
}