Another Java Solution.Recursion.


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

Log in to reply
 

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