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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
return its minimum depth = 2.
Solution: Recursion¶
Time complexity: O(n) Space complexity: O(n)
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
if (!root->left && !root->right) return 1;
int l = root->left ? minDepth(root->left) : INT_MAX;
int r = root->right ? minDepth(root->right) : INT_MAX;
return min(l, r) + 1;
}
};
Queue version
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
int count = 0;
while (q.size() > 0) {
int n = q.size();
count ++;
boolean end = false;
for (int i = 0; i < n; i ++) {
TreeNode node = q.remove();
if (node.left == null && node.right == null) {
end = true;
}
if (node.left != null) {
q.add(node.left);
}
if (node.right != null) {
q.add(node.right);
}
}
if (end == true) {
break;
}
}
return count;
}
}