Need advice on this- my code is breaking for the case{ tree =[1,2,null] and Sum = 1}


  • 0
    S
    enter code here
    

    public class Solution {

    public boolean check = false ; 
    
    public boolean hasPathSum(TreeNode root, int sum) {
    int val =  0  ; 
    if(root == null ) {return false ;}
    
    if(root.left == null && root.right == null){
    if(root.val == sum){return true ;}
    }
    hasPathSumVal(root,sum,val);
    
    
     return check ;
    }
    
    public void hasPathSumVal(TreeNode root, int sum ,int val) {
        
     if(root == null){if(sum==val){check = true;} return;}
     val = val+root.val;
     hasPathSumVal(root.left,sum,val);
     hasPathSumVal(root.right,sum,val);
     
    }

  • 2
    R

    Well! In your test case, [1,2,null] and sum = 1, there is only one path (1,2) according to the problem description. But your code considers the other path (1,null) also and return true. You are checking the node whether it is null after you are entering into it. By doing so, you lose the ability to check whether you have to enter into it or not. You can avoid checking the null, if you recurse only if the node is not null. i.e. just change the function hasPathSumVal to this.

    public void hasPathSumVal(TreeNode root, int sum ,int val) {
     val = val+root.val;
     if(root.left == null && root.right==null){if(sum==val){check = true;} return;}
     if(root.left!=null) hasPathSumVal(root.left,sum,val);
     if(root.right!=null) hasPathSumVal(root.right,sum,val);
    }
    

    The only changes it has from your solution are the null checks and the placement of the addition.

    Hope this helps.


  • 0
    S

    Thank you for helping Ravikanth :-)


Log in to reply
 

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