题目:
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,
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
翻译:
给定一个二叉树和一个和sum,检测这个二叉树是否存在一个从根节点到叶子节点的路径,每个节点的和加起来是sum。
分析:
这道题目实现起来并不复杂,但有一些特殊取值的定义,题目说的不是很清楚,比如是空树的时候,返回什么,根据OJ的结果,空树是直接返回false的。还有一个可能出错的地方是在叶子节点的判断上,例如”[1,2] sum=1”这个输入,”1”这个节点有左子树”2”而没有右子树,而计算到”1” 这个节点时值刚刚是sum的1,笔者的第一版程序返回了true,但实际上这个节点并不是一个叶子节点。
代码:
/**
* 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;
}else{
if(root.left==null&&root.right==null&&sum==root.val){
return true;
}
if(hasPathSum(root.left, sum-root.val)){
return true;
}
if(hasPathSum(root.right, sum-root.val)){
return true;
}
}
return false;
}
}