24、路径总和

题目描述
24、路径总和
我的思路:首先查看的是根节点,然后用num-根节点的值,并且要考虑到节点是否为空
需要注意的是这里的递归要注意,二叉树基本都是递归来实现

	//再一次使用递归
		public static  boolean hasPathSum(TreeNode root, int sum) {
				if(root == null){
					return false;
				}else {
					int i = sum - root.val;
					if(root.left == null && root.right == null){
						return i == 0? true:false;
					}
					return hasPathSum(root.left, i)||hasPathSum(root.right, i);
				}
       }

排名比较高的代码,我感觉思路都差不多,为什么时间能差这么多???

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null){
            return false;
        }
        return decide(root,sum);
    }
    public boolean decide(TreeNode root, int sum){
         if(root==null){
             return false;
         }
         if(root.left==null&&root.right==null&&root.val==sum){
             return true;
         }
         return decide(root.left,sum-root.val)|| decide(root.right,sum-root.val);
    }
}