题目
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.
题意
给定一个二叉树和一个sum(和),确定从根到叶子结点的路径上,是否存在某个路径上的数字之和等于给定的数字。
比如(上图给定sum = 22): 5->4->11->2
的和是22.
分析及代码
- 【要素】 对于空结点的判断,对于叶子结点的判断,对于和的判断。
- 【逻辑】因为是是否存在的问题,所以使用 或 (“||”)。
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return getResult(root, 0, sum);
}
public boolean getResult(TreeNode root,int pre,int sum){
if(root == null) {
return false;
}
int realSum = root.val +pre;
if(root.left == null && root.right == null){
return realSum == sum;
}
return getResult(root.left, realSum, sum)||getResult(root.right, realSum, sum);
}
}