从菜鸟到大牛一定要戒骄戒躁,沉下心来慢慢打磨自己!
这个题目的算法思想分为三种情况:
case1树为空时,返回false
case2 树只有一个根节点
case3 正常情况下的树
Java代码如下:
/**
* 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) {
//case1 the tree is null
if(root==null)return false;
//case2 the tree has only one node
sum=sum-root.val;
if((root.left==null)&&(root.right==null))return sum==0;
//case3 nomal case
return hasPathSum(root.left,sum)||hasPathSum(root.right,sum);
}
}