Clear java solution you should see it .


  • 0
    J
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
       public static boolean hasPathSum(TreeNode root, int sum) {
           if(root==null) return false;
               //sub node val.when sum is 0 and the node is leaf,we find the path.
    		sum -= root.val;
    		//leaf 
    		if (root.left == null && root.right == null) {
    			if (sum == 0)
    				return true;
    		} else {
    			if (root.left != null)
    				 if(hasPathSum(root.left, sum))
    					 return true;
    			if (root.right != null)
    				 if(hasPathSum(root.right, sum))
    					 return true;
    		}	
                //arrive to leaf,but sum is not 0,so we must plus node val
    		sum += root.val;
    		return false;
    	}
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.