Skip to content

How to Fix Maximum Depth of Binary Tree Errors

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about How to Fix Maximum Depth of Binary Tree Errors. We cover key concepts, practical examples, and best practices.

Fix maximum depth of binary tree errors when null handling or recursion base case returns wrong values.

Quick Fix

Wrong

def max_depth(r):
    if not r: return -1
    return 1+max(max_depth(r.left),max_depth(r.right))

Returns -1 for empty tree instead of 0.

def max_depth(r):
    if not r: return 0
    return 1+max(max_depth(r.left),max_depth(r.right))
[3,9,20,null,null,15,7] -> 3. O(n).

Prevention

Return 0 for empty tree. Add 1 for current node at each level.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is max depth?

Nodes on longest path from root to leaf. Empty tree depth is 0.

Why 0 not -1?

Empty tree has 0 depth. Single node depth 1. -1 conflates with negative.

Iterative?

Level-order BFS counting levels.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro