105 construct BST from preorder and inorder(inorder and postorder)

preoder保存的都是头结点,依次取出来作为ROOT节点,然后在inorder数组里面找出当前preoder[i]的下标,
之后在[inorder+index+1, end] [0, inorder+index-1] 分别构造右树和左树

int searchNode(int inorder[], int inorderSize, int key){
    int i;
    for (i = 0; i < inorderSize; i++) {
        if (key == inorder[i]) {
            return i;
        }
    }
    return -1;
}

struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {

    if (preorder == NULL || inorder == NULL
        || preorderSize == 0 || inorderSize == 0) return NULL;

    struct TreeNode *root
        = (struct TreeNode *)malloc(sizeof(struct TreeNode));
    root->val = preorder[0];

    int index = searchNode(inorder, inorderSize, preorder[0]);
    if (index == -1) return NULL;

    root->left = buildTree(preorder + 1, index, inorder, index);
    root->right = buildTree(preorder + index + 1, inorderSize - index - 1,
                            inorder + index + 1, inorderSize - index - 1);

    return root;
}

你可能感兴趣的:(105 construct BST from preorder and inorder(inorder and postorder))