Skip to content

111. Minimum Depth of Binary Tree 👍

Approach 1: Top-down DFS

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  int minDepth(TreeNode* root) {
    if (root == nullptr)
      return 0;
    if (root->left == nullptr)
      return minDepth(root->right) + 1;
    if (root->right == nullptr)
      return minDepth(root->left) + 1;
    return min(minDepth(root->left), minDepth(root->right)) + 1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public int minDepth(TreeNode root) {
    if (root == null)
      return 0;
    if (root.left == null)
      return minDepth(root.right) + 1;
    if (root.right == null)
      return minDepth(root.left) + 1;
    return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def minDepth(self, root: TreeNode | None) -> int:
    if not root:
      return 0
    if not root.left:
      return self.minDepth(root.right) + 1
    if not root.right:
      return self.minDepth(root.left) + 1
    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1

Approach 2: Bottom-up BFS

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int minDepth(TreeNode* root) {
    if (root == nullptr)
      return 0;

    queue<TreeNode*> q{{root}};

    for (int step = 1; !q.empty(); ++step)
      for (int sz = q.size(); sz > 0; --sz) {
        TreeNode* node = q.front();
        q.pop();
        if (node->left == nullptr && node->right == nullptr)
          return step;
        if (node->left)
          q.push(node->left);
        if (node->right)
          q.push(node->right);
      }

    throw;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int minDepth(TreeNode root) {
    if (root == null)
      return 0;

    Queue<TreeNode> q = new ArrayDeque<>(List.of(root));

    for (int step = 1; !q.isEmpty(); ++step)
      for (int sz = q.size(); sz > 0; --sz) {
        TreeNode node = q.poll();
        if (node.left == null && node.right == null)
          return step;
        if (node.left != null)
          q.offer(node.left);
        if (node.right != null)
          q.offer(node.right);
      }

    throw new IllegalArgumentException();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def minDepth(self, root: TreeNode | None) -> int:
    if not root:
      return 0

    q = collections.deque([root])

    step = 1
    while q:
      for _ in range(len(q)):
        node = q.popleft()
        if not node.left and not node.right:
          return step
        if node.left:
          q.append(node.left)
        if node.right:
          q.append(node.right)
      step += 1