Accepted Java Solution


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

    }


Log in to reply
 

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