Share my neat Java solution


  • 3
    I
    public class Solution {
        private int sum;
        
        public Solution() {
            sum = 0;
        }
        public void sumNumbersHelper(TreeNode root, int current) {
            if (root == null) return;
            current = current * 10 + root.val;
            if (root.left == null && root.right == null) {
                sum += current;
            } else {
                sumNumbersHelper(root.left, current);
                sumNumbersHelper(root.right, current);
            }
        }
        
        public int sumNumbers(TreeNode root) {
            if (root == null) return sum;
            int current = 0;
            sumNumbersHelper(root, current);
            return sum;
        }
    }

Log in to reply
 

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