Java: Returns 4 instead of 3 - DFS


  • 0
    D

    This solution is same as a lot of submissions, but it returns 4 instead of 3.
    Can some one please help me understand why my code does not work as expected?
    '''
    /**

    • Definition for a binary tree node.
    • public class TreeNode {
    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public int pathSum(TreeNode root, int sum) {
      int path = 0;
      if(root.val == sum)
      return 1;
      else if(root.left == null && root.right == null)
      return 0;
      if(root.left != null){
      path += pathSum(root.left, sum - root.val);
      path += pathSum(root.left, sum);
      }
      if(root.right != null){
      path += pathSum(root.right, sum - root.val);
      path += pathSum(root.right, sum);
      }
      return path;
      }
      }
      '''

Log in to reply
 

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