LeetCode 111: Minimum Depth of Binary Tree Solution
Master LeetCode problem 111 (Minimum Depth of Binary Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
111. Minimum Depth of Binary Tree
Problem Explanation
Explanation
To find the minimum depth of a binary tree, we can perform a depth-first search (DFS) traversal. We will keep track of the depth of each node as we traverse the tree. At each node, we will check if it is a leaf node (i.e., a node with no children). If it is a leaf node, we will update the minimum depth found so far. We will continue this process for all nodes in the tree until we have visited all nodes.
Algorithm:
- Start a DFS traversal from the root node.
- At each node, check if it is a leaf node.
- If it is a leaf node, update the minimum depth if the current depth is less than the previously found minimum depth.
- Recursively traverse the left and right children of the current node.
- Return the minimum depth found.
Time Complexity:
The time complexity of this algorithm is O(n) since we visit each node in the tree exactly once.
Space Complexity:
The space complexity is O(h) where h is the height of the tree. In the worst-case scenario, the space complexity can be O(n) for a skewed tree.
Solution Code
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int minDepth = Integer.MAX_VALUE;
if (root.left != null) {
minDepth = Math.min(minDepth, minDepth(root.left));
}
if (root.right != null) {
minDepth = Math.min(minDepth, minDepth(root.right));
}
return minDepth + 1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 111 (Minimum Depth of Binary Tree)?
This page provides optimized solutions for LeetCode problem 111 (Minimum Depth of Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 111 (Minimum Depth of Binary Tree)?
The time complexity for LeetCode 111 (Minimum Depth of Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 111 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 111 in Java, C++, or Python.