Leetcode 111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
A leaf is a node with no children.
For example, given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth which is 2.
nullptr
)?
0
since there are no nodes in the tree.Let’s implement the BFS approach for simplicity and efficiency in finding the shortest path.
#include <queue>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;
std::queue<TreeNode*> q;
q.push(root);
int depth = 1;
while (!q.empty()) {
int levelSize = q.size();
for (int i = 0; i < levelSize; ++i) {
TreeNode* currentNode = q.front();
q.pop();
// Check if it's a leaf node
if (currentNode->left == nullptr && currentNode->right == nullptr) {
return depth;
}
// Add left and right children to the queue if they exist
if (currentNode->left != nullptr) q.push(currentNode->left);
if (currentNode->right != nullptr) q.push(currentNode->right);
}
++depth; // Increment depth at the end of each level
}
return depth;
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?