C++ 19ms to solve it,just like the first problem


  • 2
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > result; 
        vector<int> vec;
        inOrderTrav(root,vec,sum,result);
        return result;
    }
    
    bool inOrderTrav(TreeNode *root,vector<int> &vec,const int &sum,vector<vector<int> > &result)
    {
        if(root!=NULL)
        {
            vec.push_back(root->val);
            if(root->left!=NULL)
                if(inOrderTrav(root->left,vec,sum,result))
                    return true;
            if(root->right!=NULL)
                if(inOrderTrav(root->right,vec,sum,result))
                    return true;
            if(root->left==NULL&&root->right==NULL&&cal(vec)==sum)
                result.push_back(vec);
            vec.pop_back();
        }
        return false;
    }
    
    int cal(vector<int> &vec)
    {
        vector<int>::iterator ive = vec.begin();
        int root_to_leaf = 0;
        for(;ive!=vec.end();ive++)
        {
            root_to_leaf += *ive;
        }
        return root_to_leaf;
    }

Log in to reply
 

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