I、Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
PS:要想好判断条件,递归的时候考虑到必须要到子节点。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if(root==NULL) return false;
return dfs(root,sum);
}
bool dfs(TreeNode *root, int sum){
if(root==NULL) return false;
if(root->left==NULL&&root->right==NULL&&sum==root->val) return true;
return dfs(root->left,sum-root->val)||dfs(root->right,sum-root->val);
}
};
II、
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 andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
/**
* Definition for binary tree
* 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) {
dfs(root,sum);
return res;
}
void dfs(TreeNode *root, int sum){
if(root==NULL) return;
v.push_back(root->val);
if(root->left==NULL&&root->right==NULL&&root->val==sum){
res.push_back(v);
}else{
dfs(root->left,sum-root->val);
dfs(root->right,sum-root->val);
}
v.pop_back();
}
vector<int> v;
vector<vector<int>> res;
};