Fast & Easy to understand JAVA solution (using recursive) took 242 ms


  • 1
    A
    public class Solution {
        
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root == null) return false;
            TreeNode current = root;
            int remaining = sum-root.val;
            boolean left = false;
            boolean right = false;
            
            if(root.left!= null)
            {
                left = hasPathSum(root.left, remaining);
            }
            
            if(root.right != null)
            {
                right = hasPathSum(root.right, remaining);
            }
            
            if(root.left == null && root.right == null && remaining == 0) return true;
            return (left || right);
        }
    }
    

    can anyone suggest anything to optimize it?


Log in to reply
 

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