问题描述:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
原问题链接:https://leetcode.com/problems/path-sum/
问题分析
这个问题的关键在于找到问题中的一个递归关系。因为如果要判断从根节点到某个叶节点是否存在这么一个节点值的和等于目标值,我们可以从一个节点当前的值和目标值判断。如果当前值已经是叶节点,而且和目标值相等,则返回true。否则同时递归的去看它的左右子节点和目标值的关系。
这里还有一个要注意的返回条件,就是当当前节点是null的时候,直接返回false。
详细的代码实现如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if(root.val == sum && root.left == null && root.right == null) return true;
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}