30 ms concise Java solution


  • 0
    L
    public int pathSum(TreeNode root, int sum) {
            if (root == null) {
                return 0;
            }
    
            return pathSum(root, sum, true);
        }
    
        public int pathSum(TreeNode root, int sum, boolean noStartNode) {
            int result = 0;
    
            if (root == null) {
                return result;
            }
    
            if (root.val == sum) {
    //            System.out.println("node=" + root + "\t sum=" + sum);
                result++;
            }
    
            if (noStartNode) {
                result += pathSum(root.left, sum, true);
                result += pathSum(root.right, sum, true);
            }
    
            result += pathSum(root.left, sum - root.val, false);
            result += pathSum(root.right, sum - root.val, false);
    
            return result;
        }
    

Log in to reply
 

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