Simple c sulotion in 3ms, beats 100%


  • 0
    J
    /**cpp
     * 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* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
        if (preorderSize == 0) {
            return NULL;
        }
        return _buildTree(preorder, preorderSize, inorder, inorderSize);
    }
    struct TreeNode* _buildTree(int* preorder, int preorderSize, int* inorder, int index) {
        struct TreeNode* result = (struct TreeNode*)malloc(sizeof(struct TreeNode));
        int val = result->val = *preorder;
        while (index--) {
            if (inorder[index] == val) {
                break;
            }
        }
        result->left = index == 0 ? NULL : _buildTree(preorder + 1, index, inorder, index);
        result->right = preorderSize - index - 1 == 0 ? NULL : _buildTree(preorder + index + 1, preorderSize - index - 1, inorder + index + 1, preorderSize - index - 1);
        return result;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.