解题思路
要观察给的方法,给了总数,一直减就好了。另外要注意出口问题。其他的就是分解树的问题。初次做,我花太多时间在分解树的问题上了。
/**
* 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 {
private int sum = 0;
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
} else if (root.left == null && root.right == null && targetSum == root.val) {
return true;
} else {
if (hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val)) {
return true;
} else {
return false;
}
}
}
}