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.
思路:递归。递归结束条件:左右子树都为空且 这一次调用函数的sum 和 当前root的val相等。
递归调用时,第二个参数用sum-root->val,这样后面直接判断给定的这个值和下一层节点是否相等就可以了。
代码:
/**
* 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;
if(root->left==NULL && root->right==NULL && sum-root->val==0)
return true;
return hasPathSum(root->left,sum-root->val) || hasPathSum(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]
]
思路同上,定义vector来存放答案
代码:
/**
* 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) {
vector<vector<int> > res;
vector<int> temp;
sumhelper(root,sum,temp,res);
return res;
}
void sumhelper(TreeNode *root,int sum,vector<int> temp,vector<vector<int> >& res){
if(root==NULL)
return;
temp.push_back(root->val);
if(root->left==NULL && root->right==NULL && sum-root->val==NULL)
res.push_back(temp);
sumhelper(root->left,sum-root->val,temp,res);
sumhelper(root->right,sum-root->val,temp,res);
}
};