My C++ solution


  • 0
    S
    class Solution {
    public:
        
        TreeNode* build(vector<int>& preorder, vector<int>& inorder, int l, int h) {
            static int preIdx = 0;
            if (l>h) return NULL;
            TreeNode* node = new TreeNode(preorder[preIdx++]);
            
            if(l==h) return node;
            
            int inIdx;
            
            
            for(int i =l; i<=h;i++) {
                if(inorder[i]==node->val) {
                    inIdx=i;
                    break;
                }
            }
            node->left = build(preorder,inorder,l,inIdx-1);
            node->right = build(preorder,inorder,inIdx+1,h);
            
            return node;
        }
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {    
            TreeNode* node = build(preorder, inorder, 0, inorder.size()-1);
            return node;
        }
    };
    

Log in to reply
 

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