Practice › Trees
Minimum Depth of a Binary Tree
Easy · Trees · Asked at Amazon, Microsoft, TCS, Infosys
Print the minimum depth of the tree — the number of nodes on the shortest path from the root down to a leaf (a node with no children).
Input
First line: k. Second line: k values — the tree in level order, -1 means no node.
Output
The minimum depth.
Constraints
- 1 ≤ number of nodes ≤ 10^5
- values are positive
BFS level by level and stop at the first leaf. Careful with recursion: a node with only one child is not a leaf, so min(left, right) must ignore a missing side.
Example 1
Input
7 3 9 20 -1 -1 15 7
Output
2
Example 2
Input
9 2 -1 3 -1 4 -1 5 -1 6
Output
5
Hints
- BFS visits nodes in order of depth.
- The first leaf BFS reaches is the closest one.
- In a recursive solution, a missing child must not count as a depth-0 leaf.
Approach
BFS from the root, storing the depth with each node. The first node with no children that comes out of the queue is the nearest leaf, so its depth is the answer — and the search stops early without visiting the deeper parts of the tree.
Complexity: O(n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
// level order with -1 for a missing child
Node *build(const vector<long long> &a) {
if (a.empty() || a[0] == -1) return nullptr;
Node *root = new Node(a[0]);
queue<Node *> q;
q.push(root);
size_t i = 1;
while (!q.empty() && i < a.size()) {
Node *cur = q.front();
q.pop();
if (i < a.size() && a[i] != -1) q.push(cur->left = new Node(a[i]));
i++;
if (i < a.size() && a[i] != -1) q.push(cur->right = new Node(a[i]));
i++;
}
return root;
}
vector<long long> readTree() {
int k;
cin >> k;
vector<long long> a(k);
for (auto &x : a) cin >> x;
return a;
}
int main() {
Node *root = build(readTree());
queue<pair<Node *, int>> q;
q.push({root, 1});
while (!q.empty()) {
auto _b = q.front();
auto n = _b.first;
auto d = _b.second;
q.pop();
if (!n->left && !n->right) {
cout << d << "\n";
return 0;
}
if (n->left) q.push({n->left, d + 1});
if (n->right) q.push({n->right, d + 1});
}
return 0;
}Python solution
import sys
from collections import deque
class Node:
__slots__ = ("val", "left", "right")
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def build(a):
"""Level order with -1 for a missing child."""
if not a or a[0] == -1:
return None
root = Node(a[0])
q = deque([root])
i = 1
while q and i < len(a):
cur = q.popleft()
if i < len(a) and a[i] != -1:
cur.left = Node(a[i])
q.append(cur.left)
i += 1
if i < len(a) and a[i] != -1:
cur.right = Node(a[i])
q.append(cur.right)
i += 1
return root
data = list(map(int, sys.stdin.read().split()))
root = build(data[1 : 1 + data[0]])
q = deque([(root, 1)])
while q:
node, d = q.popleft()
if not node.left and not node.right:
print(d)
break
if node.left:
q.append((node.left, d + 1))
if node.right:
q.append((node.right, d + 1))Java solution
import java.io.*;
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
// level order with -1 for a missing child
static Node build(long[] a) {
if (a.length == 0 || a[0] == -1) return null;
Node root = new Node(a[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < a.length) {
Node cur = q.poll();
if (i < a.length && a[i] != -1) q.add(cur.left = new Node(a[i]));
i++;
if (i < a.length && a[i] != -1) q.add(cur.right = new Node(a[i]));
i++;
}
return root;
}
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static long next() throws IOException {
in.nextToken();
return (long) in.nval;
}
static long[] readTree() throws IOException {
int k = (int) next();
long[] a = new long[k];
for (int i = 0; i < k; i++) a[i] = next();
return a;
}
public static void main(String[] args) throws IOException {
Node root = build(readTree());
ArrayDeque<Object[]> q = new ArrayDeque<>();
q.add(new Object[] {root, 1});
while (!q.isEmpty()) {
Object[] t = q.poll();
Node n = (Node) t[0];
int d = (int) t[1];
if (n.left == null && n.right == null) {
System.out.println(d);
return;
}
if (n.left != null) q.add(new Object[] {n.left, d + 1});
if (n.right != null) q.add(new Object[] {n.right, d + 1});
}
}
}Solve Minimum Depth of a Binary Tree online · All practice problems