路径和 path-sum
题目描述
给定一个二叉树和一个值sum,判断是否有从根节点到叶子节点的节点值之和等于sum的路径,
例如:
给出如下的二叉树,sum=22,
返回true,因为存在一条路径5->4->11->2的节点值之和为22
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,
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
解题思路
1.递归求解
- 如果root为NULL,则返回false
- 如果到达叶节点,且sum减去当前叶节点的值为0,则返回true
- 其余情况继续递归求解左右子树
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
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);
}
};
2.回溯法
- 路径:不需要记录
- 选择列表:不空的左右子树
- 结束条件:如果root为空,直接返回,如果root为叶节点,则当
sum - root -> val == 0
时返回true
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
bool res = false;
/*由于要从根节点的子树开始判断,所以要先单独对根节点进行判断*/
if(root == NULL) return false;
backtrack(root, sum, res);
return res;
}
void backtrack(TreeNode* root, int& sum, bool& res) {
if(root == NULL)
return ;
//如果到达叶子节点,且满足条件
if(root -> left == NULL && root -> right == NULL && sum - root -> val == 0) {
res = true;
return ;
}
//两个选择,只要子树不空就做选择
if(root -> left != NULL) {
sum -= root -> val;
backtrack(root -> left, sum, res);
sum += root -> val;
}
if(root -> right != NULL) {
sum -= root -> val;
backtrack(root -> right, sum, res);
sum += root -> val;
}
}
};
- 由于此题不用记录路径,所以可以不用到回溯,仅需要dfs即可
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
bool res = false;
if(root == NULL) return false;
dfs(root, sum, res);
return res;
}
void dfs(TreeNode* root, int sum, bool& res) {
if(root == NULL)
return ;
//如果到达叶子节点,且满足条件
if(root -> left == NULL && root -> right == NULL && sum - root -> val == 0) {
res = true;
return ;
}
//两个选择,只要子树不空就做选择
if(root -> left != NULL) {
dfs(root -> left, sum - root -> val, res);
}
if(root -> right != NULL) {
dfs(root -> right, sum - root -> val, res);
}
}
};