Even Neater and easy to understand java solution


  • 3
    B
    int totalSum = 0;
    
    public int sumNumbers(TreeNode root) {
        sum(root, 0);
        return totalSum;
    }
    
    public void sum(TreeNode root, int sum) {
        if (root == null) return;
        
        sum = sum * 10 + root.val;
        
        if (root.left == null && root.right == null) {
            totalSum += sum;
            return;
        }
        
        sum(root.left, sum);
        sum(root.right, sum);
    }

  • 1
    A
    public class Solution {
        public int SumNumbers(TreeNode root) {
            return sumNum(root, 0);
        }
        private int sumNum(TreeNode root, int sum){
            if (root==null) {return 0;}
            sum = sum*10 + root.val;
            if (root.left==null && root.right==null){
                return sum;
            }
            return sumNum(root.left, sum) + sumNum(root.right, sum);
        }
    }
    

    I tried to return the sum.


Log in to reply
 

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