1. 题目描述
- 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.
- 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 1
- return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
- return
[
[5,4,11,2],
[5,8,4,5]
]
2. 解题思路
拿到这个问题, 虽然是一颗树, 不过我们可以将它看成是一个搜索问题, 使用回溯法(相当于 DFS 搜索)即可。
3. code
// path sum
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (root == nullptr){
return false;
}
return _hasPathSum(root, sum);
}
private:
bool _hasPathSum(TreeNode* root, int sum) {
//if (sum < 0)
// return false;
if (!root->left && !root->right){
return sum == root->val ? true : false;
}
bool ret = false;
if (root->left)
ret = _hasPathSum(root->left, sum - root->val);
if (!ret && root->right)
ret = _hasPathSum(root->right, sum - root->val);
return ret;
}
};
// path sum ii
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
//vector<vector<int>> res;
if (root)
_hasPathSum(root, sum);
return res;
}
private:
void _hasPathSum(TreeNode* root, int sum) {
if (!root->left && !root->right){
if (sum == root->val){
path.push_back(root->val);
res.push_back(path);
path.pop_back();
}
return;
}
path.push_back(root->val);
if (root->left)
_hasPathSum(root->left, sum - root->val);
if (root->right)
_hasPathSum(root->right, sum - root->val);
path.pop_back();
return;
}
vector<vector<int>> res;
vector<int> path;
};
4. 大神解法
4.1 path sum
类似的思想, 不过代码更精简
bool hasPathSum(TreeNode *root, int sum) {
if (root == NULL) return false;
if (root->val == sum && root->left == NULL && root->right == NULL) return true;
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}