Java solution using recursion and backtracking. No globals and only one function.


  • 0
    V
    public int sumNumbers(TreeNode root) {
            if(root == null) return 0;
            if(root.left == null && root.right == null){
              int result = root.val;
              root.val = root.val % 10; // backtracking 
              return result;  
            } 
            root.val *= 10;
            int sum = 0;
            if(root.left != null){
                root.left.val = root.val + root.left.val;
                sum += sumNumbers(root.left);
            }
            if(root.right != null){
                root.right.val = root.val + root.right.val;
                sum += sumNumbers(root.right);
            } 
            root.val /= 10; // backtracking  
            
            return sum;
        }
    

Log in to reply
 

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