My java solution - any improvements, please suggest Thanks !!


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

Log in to reply
 

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