每天一道LeetCode >> 统计路径和等于一个数的路径数量

原题题目:You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
在这里插入图片描述
注意:题目中要求统计路径和等于一个数的路径数量,并且路径不是必须从根节点开始或者以叶子节点结束,也就是还包含从某一节点开始以另一节点结束的路径,但是必须是连续的节点

  1. 由于都是想在该节点下进行条件是否满足的判断,以及sum值的变更,因此我们很自然的想到了递归。在当前节点满足等于sum的状况下,就进行路径和数量的加1。
  2. 由于本题中声明路径不是必须包括根节点和叶子节点,因此我们不能只关注从根节点开始的路径,比如下图:
    在这里插入图片描述可以看到有三条路径,因此除了根节点,我们还要从所有的非空节点开始搜索,避免落下每一条路径。
    附上代码:
	public static int pathSum(TreeNode root, int sum) {
	    if (root == null) 
	    	return 0;
	    int ret = helper(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
	    return ret;
	}

	private static int helper(TreeNode root, int sum) {
	    if (root == null) 
	         return 0;
	    int ret = 0;
	    // 在满足的情况下就+1
	    if (root.val == sum) 
	         ret++;
	    ret += helper(root.left, sum - root.val) + helper(root.right, sum - root.val);
	    System.out.println(root.val + "对应的路径的数目值" + ret);
	    return ret;
	}
	public static void main(String[] args) {
		TreeNode tree1 = new TreeNode(5);
		TreeNode tree2 = new TreeNode(4);
		TreeNode tree3 = new TreeNode(11);
		TreeNode tree4 = new TreeNode(7);
		TreeNode tree5 = new TreeNode(2);
		tree1.left = tree2;
		tree2.left = tree3;
		tree3.left = tree4;
		tree3.right = tree5;
		System.out.println(pathSum(tree1, 18));
	}

附上结果图:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值