首页 > 代码库 > LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal

LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal

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

Note:
You may assume that duplicates do not exist in the tree.

 

Subscribe to see which companies asked this question

解答

/**
 * 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) {
    struct TreeNode *node;
    int i;
    
    if(0 >= preorderSize||0 >= inorderSize){
        return NULL;
    }
    node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    node->val = preorder[0];
    for(i = 0; i < inorderSize; i++){
        if(inorder[i] == preorder[0]){
            break;
        }
    }
    node->left = buildTree(preorder + 1, i, inorder, i);
    node->right = buildTree(preorder + i + 1, preorderSize - 1 - i, inorder + i + 1, preorderSize - 1 - i);
    return node;
}

 

LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal