路径总和 --java记录

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 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);
	 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值