这道题用recursive的方法比较简洁,代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
// Corner case
if(root == null){
return false;
}
// Base case: reach a leaf node
if(root.left == null && root.right == null){
return sum - root.val == 0;
}
// Recursive rule
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}