113. Path Sum II

来源:互联网 发布:手机淘宝宝贝描述模板 编辑:程序博客网 时间:2024/06/13 08:55

1、题目描述

给出一个二叉树和一个target,返回所有从根节点到叶子节点和为target的序列。


2、思路

DFS。


3、代码

    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int>> ans;        if(!root) return ans;        vector<int> v;        v.push_back(root->val);        dfs(ans,v,root,sum-(root->val));        return ans;    }    void dfs(vector<vector<int>>& ans,vector<int>& v,TreeNode* root, int sum){        if(sum==0&&(root->left==NULL&&root->right==NULL)){            ans.push_back(v);            return;        }        if(root->left){            v.push_back(root->left->val);            dfs(ans,v,root->left,sum-(root->left->val));            v.pop_back();        }                if(root->right){            v.push_back(root->right->val);            dfs(ans,v,root->right,sum-(root->right->val));            v.pop_back();        }    }