Big O Gym › Problem

Big O Practice: Max Depth Binary Tree

Time and space complexity practice in Python and JavaScript. Concept tested: tree recursion: nodes vs stack depth.

def max_depth(node):
    if not node:
        return 0
    left = max_depth(node.left)
    right = max_depth(node.right)
    return 1 + max(left, right)

Variables

  • n - number of nodes in the tree
  • h - height of the tree

Explanation

Every node is visited exactly once, **O(n)** time. The recursion stack depth is the tree height **O(h)** - `log n` balanced, `n` degenerate.

More Big O practice problems · Today's daily problem