Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
思路:深度优先搜索。这道题和上一题差不多,就是dfs找到所有的结果就可以。每次把根节点放到path,如果不对再弹出,并且可以找到多个path,都返回到result.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>>result;
vector<int>path;
dfs(root,sum,path,result);
return result;
}
void dfs(TreeNode* root,int gap,vector<int>path, vector<vector<int>>&result){
if(!root) return;
path.push_back(root->val);
if(!root->left&&!root->right){
if(gap==root->val){
result.push_back(path);
}
}
dfs(root->left,gap-root->val,path,result);
dfs(root->right,gap-root->val,path,result);
path.pop_back();
}
};