An accepted C++ recursion solution


  • 0
    B
    class Solution {
    public:
        vector<vector<int> > pathSum(TreeNode *root, int sum) {
            
            if ( root == NULL ) {
                vector<vector<int> > null;
                return null;
            }
            if ( root->left == NULL && root->right == NULL && sum == root->val ) {
                vector<int> v;
                vector<vector<int> > vc;
                v.push_back(sum);
                vc.push_back(v);
                return vc;
            }
            vector<vector<int> > vLeft = pathSum(root->left,sum-root->val);
            vector<vector<int> > vRight = pathSum(root->right,sum-root->val);
            vector<vector<int> > v;
    
            for ( int i = 0; i < vLeft.size(); i++ ) {
    
                vLeft[i].insert(vLeft[i].begin(),root->val);
                v.push_back(vLeft[i]);
            }
            for ( int i = 0; i < vRight.size(); i++ ) {
    
                vRight[i].insert(vRight[i].begin(),root->val);
                v.push_back(vRight[i]);
            }
            return v;
        }
    };

Log in to reply
 

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