也是遍历一遍二叉树的路径,每次遍历一个节点就把targeSum
减去对应的节点值,如果最后是叶子节点并且targeSum
为0,则符合条件
class Solution { public: bool flag = false; void dfs(TreeNode* cur, int sum, int targetSum) { //判断条件 if (sum == targetSum && !cur->left && !cur->right) { flag = true; return; } else { //分别向左右子树遍历 if (cur->left) dfs(cur->left, sum + cur->left->val, targetSum); if (cur->right) dfs(cur->right, sum + cur->right->val, targetSum); } } bool hasPathSum(TreeNode* root, int targetSum) { if (root == nullptr)return false; dfs(root, root->val, targetSum); if (flag)return true; else return false; } };