剑指 Offer 34. 二叉树中和为某一值的路径
dfs
class Solution {
public:
vector<vector<int>>res;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(!root) return res;
vector<int>path;
dfs(root,path,sum);
return res;
}
void dfs(TreeNode *root,vector<int> &path,int sum){
sum-=root->val;
path.push_back(root->val);
if(root->left==NULL && root->right==NULL){
if(sum==0) res.push_back(path);
path.pop_back();
return;
}
if(root->left)dfs(root->left,path,sum);
if(root->right)dfs(root->right,path,sum);
path.pop_back();
}
};
网友评论