My accepted recursive solution beats 65%


  • 0
    D
    public class Solution {
        public int sumNumbers(TreeNode root) {
            return sumNumbers(root,0);
        }
        public int sumNumbers(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 sum1  = sumNumbers(root.left, sum);
            int sum2 = sumNumbers(root.right, sum);
            return sum1 + sum2;
        }
    }

Log in to reply
 

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