↓Skip to main content
  1. LeetCode/

LeetCode 104: Maximum Depth of Binary Tree

·1 min· ·
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-02

  • Submissions: Accepted → Runtime Error → Accepted ×2 → Wrong Answer ×2 → Accepted → Runtime Error → Accepted ×3

Approach
#

A post-order return value (Tree Template 1): an empty tree has depth 0, otherwise 1 + max(left depth, right depth).

My Attempts
#

The first version passed. Rewriting it as a DFS with a depth parameter, a leaf returned 0 instead of the current depth ([5] returned 0), and one version returned None for an empty tree.

Solution
#

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

Complexity
#

Time O(n), space O(h).

Mistakes to Avoid
#

  • Every path of the recursive function needs a return value.

Interview Explanation
#

An empty tree has depth 0, otherwise 1 plus the deeper subtree, computed by post-order recursion. Time O(n), space O(h).

Related

LeetCode 100: Same Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 note: two empty trees are equal, one empty and one not differ, and otherwise compare values and recurse on both sides
LeetCode 101: Symmetric Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 101 note: the left and right subtrees must mirror each other, outer with outer and inner with inner; compare values, not node objects
LeetCode 144: Binary Tree Preorder Traversal
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 144 note: iterative pre-order traversal records on pop and pushes the right child before the left so the left is handled first
LeetCode 94: Binary Tree Inorder Traversal
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 94 note: iterative in-order traversal, pushing nodes while going left, recording on pop, then turning to the right subtree
LeetCode 83: Remove Duplicates from Sorted List
·2 mins
LeetCode Easy Linked-List
LeetCode 83 note: sorted, so duplicates are adjacent; skip cur.next while it equals cur, and advance only otherwise
LeetCode 69: Sqrt(x)
·1 min
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 note: find the largest mid with mid² <= x; when a closed-interval search ends, r is the answer