Skip to content

Instantly share code, notes, and snippets.

@thobbiz
Created February 11, 2026 22:19
Show Gist options
  • Select an option

  • Save thobbiz/4b4a9d0d8e6fa148d083ae8d78761938 to your computer and use it in GitHub Desktop.

Select an option

Save thobbiz/4b4a9d0d8e6fa148d083ae8d78761938 to your computer and use it in GitHub Desktop.
Maximum Depth of Binary Tree

Question

Approach

my approach was to use bottom-up --finding the depth of the subtrees for each node--. I used recursion for the approach

Algorithm

  • if root is None:
    • return 0
  • leftHeight = self.maxDepth(root.left)
  • rightHeight = self.maxDepth(root.right)
  • return 1 + max(leftDepth, rightDepth)

Implementation

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""
from typing import Optional


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        leftDepth = self.maxDepth(root.left)
        rightDepth = self.maxDepth(root.right)

        return 1 + max(leftDepth, rightDepth)
image

Complexities

  • Time: ๐‘‚(N) where N is the number of nodes
  • Space: ๐‘‚(H) where H is the height of the tree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment