Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Computing the Maximum Depth of a Binary Tree

Tech 1

Givan a binary tree, the maximum depth is the number of nodes along the longest root‑to‑leaf path. Leaf nodes are those with no children.

Depth‑First Search (Recursive)

The recursive approach computes the depth of the left and right subtreees, then takes the maximum plus one.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def tree_depth(node: TreeNode) -> int:
    if node is None:
        return 0
    left_depth = tree_depth(node.left)
    right_depth = tree_depth(node.right)
    return max(left_depth, right_depth) + 1

Time complexity: O(n) — each node is visited once.
Space complexity: O(h) where h is the height of the tree, due to the call stack (O(log n) for a balanced tree, O(n) in the worst case).

Breadth‑First Search (Iterative)

A level‑order traversal using a queue counts the number of levels. Each level represents one unit of depth.

from collections import deque

def max_depth_bfs(root: TreeNode) -> int:
    if root is None:
        return 0

    queue = deque([root])
    level = 0

    while queue:
        level += 1
        for _ in range(len(queue)):
            node = queue.popleft()
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

    return level

Time complexity: O(n) — every node is processed once.
Space complexity: O(w) where w is the maximum width of the tree (up to O(n) in the worst case).

Both methods correctly return the maximum depth for any binary tree, including edge cases like an empty tree (depth 0).

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.