Recursive java solution, with comments

  • 0
    public int sumNumbers(TreeNode root) {
        if (root == null)
            return 0;
        return sumNumbers(root, 0);  // imagine a virtual node with 0 val as root's parent
    private int sumNumbers(TreeNode root, int sum) {
        if (root.left == null && root.right == null)    // leaf node, return result
            return sum*10+root.val;
        else if (root.left == null) //  
            return sumNumbers(root.right, sum*10+root.val);
        else if (root.right == null)
            return sumNumbers(root.left, sum*10+root.val);
            return sumNumbers(root.left, sum*10+root.val) + sumNumbers(root.right, sum*10+ root.val);

Log in to reply

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