[LeetCode]112. 路径总和(java实现)
1. 题目
2. 读题(需要重点注意的东西)
思路(递归):
-
遍历到当前节点时,判断当前节点是不是叶子节点,并且当前节点的值减去targetValue是否为0,是则说明存在一条从根节点到叶子节点路径之和为targetValue的路径
-
否则继续遍历左右子树,左右子树任一成立即可。
3. 解法
---------------------------------------------------解法---------------------------------------------------:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
// 要是叶子节点
if(root.left == null && root.right == null && targetSum - root.val == 0) return true;
// 否则其左子树或者右子树中任有一成立即可
return hasPathSum(root.left,targetSum - root.val) || hasPathSum(root.right,targetSum - root.val);
}
}
可能存在的问题: