Recursive C++ code


  • 0
    class Solution {
    private:
        TreeNode* buildTree(vector<int>& preorder, int pIdx, vector<int>& inorder, int iIdx, int length ) {
            if( length <= 0 ) return nullptr;
            int i = 0, len=0;
            while( i < iIdx+length && inorder[i] != preorder[pIdx] ) len = (++i) - iIdx;
            TreeNode* root = new TreeNode(preorder[pIdx]);
            root->left = buildTree(preorder, pIdx+1, inorder, iIdx, len);
            root->right = buildTree(preorder, pIdx+len+1, inorder, iIdx+len+1, length - len - 1);
            return root;
        } 
    public:
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            return buildTree(preorder, 0, inorder, 0, inorder.size());
        }
    };
    

Log in to reply
 

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