A weird solution, no extra space, which works !


  • 0
    B

    Basically I tried to run the search such that each node is considered as root.
    So we get all the paths and sub-paths covered.
    I am sure it can be optimized,but not able to figure out how !

     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        private int c=0;
         public void pathHelper(TreeNode root, int sum, int cur)
        {
    
            if(root.val == sum)c++;
            if(root == null)
            {
                return ;
            }
             
             
             if(root.left != null)
             {
    
                path(root.left,sum,root.val);
                pathHelper(root.left,sum,0);
             }
             
    
             if(root.right != null)
             {
    
             path(root.right,sum,root.val);
             pathHelper(root.right,sum,0);
             }
        }
        public void path(TreeNode root, int sum, int cur)
        {
            if(cur+root.val == sum)
            {
                c++;
            }
            if(root == null)
            {
                return ;
            }
            
            if(root.left == null && root.right == null)
            {
                return;
            } 
            if(root.left != null )
                path(root.left,sum,cur+root.val);
    
               if(root.right != null) 
                path(root.right,sum,cur+root.val);
    
        }
        public int pathSum(TreeNode root, int sum) {
            if(root == null)return 0;
    
            
            pathHelper(root,sum,0);
            return c;
                
        }
    }```

Log in to reply
 

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