EASY NC#47 Blind #60 Trees

104. Maximum Depth of Binary Tree

๐Ÿ“– Problem

Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขRecursive stack flow
  • โ€ขCycle prevention
  • โ€ขPost-order reasoning

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply DFS reasoning pattern
  • โ€ขApply BFS reasoning pattern
  • โ€ขApply Recursion reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use DFS recursively to find maximum depth
  • โ†’ Base case: null node has depth 0
  • โ†’ Max depth = 1 + max(depth of left, depth of right)
  • โ†’ Time: O(n), Space: O(h) where h is tree height

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse DFS recursively to find maximum depth
  • โ€ขBase case: null node has depth 0
  • โ€ขMax depth = 1 + max(depth of left, depth of right)

Common Pitfalls

  • โ€ขTime: O(n), Space: O(h) where h is tree height

๐Ÿงช Test Cases

Hidden tests on submit: 3

Test Case 1
Not run
Input:
maxDepth(buildTree([3,9,20,null,null,15,7]));
Expected:
3
Test Case 2
Not run
Input:
maxDepth(buildTree([1,null,2]));
Expected:
2
Test Case 3
Not run
Input:
maxDepth(buildTree([]));
Expected:
0

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit