求路径总和,明确以下几点:
- 从根节点遍历到叶子节点,count一路减去val,当到叶子节点count正好为0时,证明这条路径就是答案,返回true
- 一旦收到true就停止遍历,找到一条答案就不找其他的了
- 当一条路径遍历完后需要回溯,count值也应该要加回来
- 在第一次进入递归函数时count就要减去root的val了。
cpp
class Solution {
public:
bool traversal(TreeNode *node, int count)
{
//判断终止条件
//1.遍历到叶子节点,count逐渐减为0
//2.遍历到叶子节点,但count不为0
if(node->left == NULL && node->right == NULL && count == 0)
{
return true;
}
if(node->left == NULL && node->right == NULL && count != 0)
{
return false;
}
//开始递归 左
if(node->left)
{
//先减去count
count = count - node->left->val;
//递归
if(traversal(node->left,count))
{
return true;
}
//回溯
count = count + node->left->val;
}
//开始递归 右
if(node->right)
{
//先减去count
count = count - node->right->val;
//递归
if(traversal(node->right,count))
{
return true;
}
//回溯
count = count + node->right->val;
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(!root) return false;
bool result = traversal(root,targetSum-root->val);
return result;
}
};