My simple C++ solution which running in 16ms and writing in 11 lines


  • 0
    class Solution {
    public:
        
        
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder,int pre_begin,int pre_end,int in_begin,int in_end) {
        if(pre_end - pre_begin<=0) return NULL;
        if(pre_end - pre_begin==1) return new TreeNode(preorder[pre_begin]);
            TreeNode* parent=new TreeNode(preorder[pre_begin]);
            int i,in_find,pre_find=pre_begin;
            for(i=in_begin;inorder[i]!=preorder[pre_begin];i++);
            in_find=i;
            pre_find=pre_begin+in_find-in_begin;
            parent->left=buildTree(preorder,inorder,pre_begin+1,pre_find+1,in_begin,in_find);
            parent->right=buildTree(preorder,inorder,pre_find+1,pre_end,in_find+1,in_end);
            return parent;
        }
        
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            return buildTree(preorder,inorder,0,preorder.size(),0,inorder.size());
        }
        
        
        
    };
    

Log in to reply
 

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