Leetcode112:路径总和

题目描述

在这里插入图片描述

思路分析

从根节点开始,每当遇到一个节点的时候,从目标值里扣除节点值,一直到叶子节点判断目标值是不是被扣完。

代码实现

package LeetCode;

public class hashPashSum {

	public static void main(String[] args) {
		
	}

	public boolean hasPathSum(TreeNode root, int sum) {
		if (root == null) 
			return false;
		
		sum -= root.val;
		if (root.left == null && root.right == null)
			return (sum == 0);
		return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
	}
}

class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;

	TreeNode(int x) {
		val = x;
	}
}
发布了88 篇原创文章 · 获赞 27 · 访问量 5908

猜你喜欢

转载自blog.csdn.net/weixin_43362002/article/details/104281170