Anyone have a solution that uses tail call recursion?


  • 0
    S

    The recursive solution is straightforward. But did anyone pass along an accumulator to allow the compiler to do some tail recursion optimization? I am not sure it's possible here since you have to recurse through both the left and right trees, but just wanted to check.


  • 1
    C

    I passed an accumulator to both the left and right recursive calls:

    public int maxDepth(TreeNode root) {
        return maxDepth(root, 0);
    }
    
    private int maxDepth(TreeNode root, int depth) {
        if (root == null) {
            return depth;
        }
    
        return Math.max(maxDepth(root.left, depth + 1), maxDepth(root.right, depth + 1));
    }

Log in to reply
 

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