16ms c++ recursion dfs solution


  • 0
    E
    class Solution {
    public:
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            vector<int> v;
            dfs(root,sum,v);
            return result;
        }
        void dfs(TreeNode* root, int sum,vector<int>& v){
            if(root==NULL)return ;
            if(root->left==NULL&&root->right==NULL){
                if(root->val==sum){
                    v.push_back(root->val);
                    result.push_back(v);
                    v.pop_back();
                }
                else return ;
            }
            v.push_back(root->val);
            dfs(root->left,sum-root->val,v);
            dfs(root->right,sum-root->val,v);
            v.pop_back();
        }
        vector<vector<int>> result;
    };
    

Log in to reply
 

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