给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
递归 - 做减法。
每次传入的的参数为sum - 节点value
直到递归到叶子节点,且 最后计算为0则返回ture。
左右子树进行递归 ,如果出现一次true则得到目标值 返回true。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public static boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
sum -= root.val;
if(root.left == null && root.right == null){
return sum == 0 ? true : false;
}
return hasPathSum(root.left, sum ) || hasPathSum(root.right, sum );
}
}
递归加法,需要两个函数
```java
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
return is(root,0,sum);
}
public boolean is(TreeNode root,int sum, int target){
if(root == null) return false;
sum += root.val;
if(root.left == null && root.right == null){
return sum == target ? true : false;
}
return is(root.left, sum ,target) || is(root.right, sum ,target);
}
}
测试
```java
public static void main(String [] args) throws InterruptedException {
TreeNode root = new TreeNode(5);
root.left = new TreeNode(4);
root.right = new TreeNode(8);
root.left.left = new TreeNode(11);
root.left.right = null;
root.left.left.left = new TreeNode(7);
root.left.left.left.right = null;
root.left.left.left.left = null;
root.left.left.right = new TreeNode(2);
root.left.left.right.right = null;
root.left.left.right.left = null;
root.right.left = new TreeNode(13);
root.right.left.right = null;
root.right.left.left = null;
root.right.right = new TreeNode(4);
root.right.right.right= new TreeNode(1);
root.right.right.left = null;
hasPathSum(root, 0);
}