LeetCode-112. Path Sum

这道题是在一次面试中,面试官让手写的代码。当时虽然思路正确,但是很多细节的地方没有注意。这道题看似简单,却让我花了比较长的时间 才AC,实在是不应该。看来基本功还需要再练习

 

 public class Solution {
    public static boolean result=false;
    
    public static boolean dfs(TreeNode root, int sum,boolean first) {

        if(first==true)
        {
             result=false;
        }

        if(root==null)
        {
            return result;
        }
        sum = sum - root.val;
        if(root.left == null && root.right ==null)
        {
                if(sum==0)
                {
                    result=true;
                }

        }

        return  dfs(root.left,sum,false) || dfs(root.right,sum,false);
    }

    public boolean hasPathSum(TreeNode root, int sum)   {
         
        return dfs(root,sum,true);
    }
}

 

posted @ 2016-03-09 14:47  SnailRen  阅读(123)  评论(0)    收藏  举报