/**
* 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) {
int count = 0;
boolean isSum = false;
isSum = countSum(root,sum,count);
return isSum;
}
private boolean countSum(TreeNode root,int sum,int count){
if(root!=null){
count = count+root.val;
if(root.left==null&&root.right==null){
if(count==sum)return true;
else return false;
}else return countSum(root.left,sum,count)||countSum(root.right,sum,count);
}else return false;
}
}
本题为一个树的问题,使用递归,中间节点的return值为其左右子节点return值取或,而最终要考虑的是叶子结点的值。