题目链接:https://leetcode.cn/problems/path-sum/description/
思路
- 递归,先序遍历二叉树,每遍历一个节点便减去当前存储值(targetSum = targetSum - root.val);
- 当到达某个节点等于targetSum (targetSum == root.val),判断该节点是否为叶子节点(root.left == null && root.right == null),如果是那么返回true;
- 如果该节点不满足targetSum,那么递归遍历左子树和右子树(hasPathSum(root.left,targetSum - root.val) || hasPathSum(root.right,targetSum - root.val)),任意一个返回true就成功。
代码实现
java
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null){ //空节点
return false;
}
if(root.left == null && root.right == null){ // 该节点为叶子节点
return targetSum == root.val; //相等则为true
}
return hasPathSum(root.left,targetSum - root.val) || hasPathSum(root.right,targetSum - root.val);
}
}