All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : June 07, 2024
Last updated : July 04, 2024
Related Topics : Tree, Depth-First Search, Breadth-First Search, Binary Tree
Acceptance Rate : 49.75 %
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int min(int a, int b) {
return (a < b) ? a : b;
}
int minDepthHelper(struct TreeNode* current) {
if (!current->left && !current->right)
return 1;
if (!current->left)
return 1 + minDepthHelper(current->right);
if (!current->right)
return 1 + minDepthHelper(current->left);
return 1 + min(minDepthHelper(current->left), minDepthHelper(current->right));
}
int minDepth(struct TreeNode* root) {
if (!root)
return 0;
return minDepthHelper(root);
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
return minDepth(root, 1);
}
private int minDepth(TreeNode curr, int depth) {
if (curr.left == null && curr.right == null) {
return depth;
}
depth++;
if (curr.left != null && curr.right != null) {
return Integer.min(minDepth(curr.left, depth), minDepth(curr.right, depth));
}
if (curr.left != null) {
return minDepth(curr.left, depth);
}
return minDepth(curr.right, depth);
}
}