My solution in java


  • 4
    S
    public class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
        	if (root==null) {return false;}
            if (root.left==null&&root.right==null){
    	        	if (sum==root.val){
    	        	 return true;
    	        	} else {
    	        	return false;}
            	}
         
            return hasPathSum(root.left,sum-root.val)||hasPathSum(root.right,sum-root.val);
    
        }
    }

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


  • 0
    Z

    Really good example of recursive solution, so simple and easy-understood. Thanks for sharing.


  • 2
    L

    great answer. it can be even more concise - instead of

    if (sum==root.val){
        return true;
        } else {
        return false;}
    

    you can just say

    return sum == root.val;

Log in to reply
 

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