Java solution, Recursive.


  • 0
    C
    public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(null == root) return false;
        int current = 0;
        
        return depthFirstSearch(root, current, sum);       
    }
    
    private boolean depthFirstSearch(TreeNode node, int current, int sum){
    	
    	//if leaf and current + node.val == sum
    	if(node.left == null && node.right == null && current + node.val == sum)
    		return true;
    
    	if(node.left != null){
    		if(depthFirstSearch(node.left, current + node.val, sum))
    			return true;
    	}
    	if(node.right != null)
    		return depthFirstSearch(node.right, current + node.val, sum);
    	//leaf, but current + node.val != sum
    	return false;
    }
    

    }


  • 0
    V
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        } else {
            if (root.left == null && root.right == null) {
                return sum == root.val;
            } else {
                int subSum = sum - root.val;
                return hasPathSum(root.left, subSum) || hasPathSum(root.right, subSum);
            }
        }
    }

Log in to reply
 

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