[LeetCode 111] Minimum Depth of Binary Tree
LeetCode 111 (Java)
[Minimum Depth of Binary Tree] 문제 풀이
[LeetCode 111] Minimum Depth of Binary Tree
Description
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 1
- Input: root = [3,9,20,null,null,15,7]
- Output: 2
Example 2
- Input: root = [2,null,3,null,4,null,5,null,6]
- Output: 5
Constraints
- The number of nodes in the tree is in the range
[0, 10^5]. -1000 <= Node.val <= 1000
Code
내 제출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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;
}
if (root.left == null) {
return 1 + minDepth(root.right);
}
if (root.right == null) {
return 1 + minDepth(root.left);
}
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
}
| Runtime | Memory |
|---|---|
| 9 ms | 63.3 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 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) {
//base case
if(root==null){
return 0;
}
//if left subtree does not exist
if(root.left==null){
return 1+minDepth(root.right);
}
//if right subtree does not exist
if(root.right==null){
return 1+minDepth(root.left);
}
//if both the sub trees exist
int leftDepth=minDepth(root.left);
int rightDepth=minDepth(root.right);
return 1+Math.min(leftDepth,rightDepth);
}
}
Reference
- https://github.com/doocs/leetcode/blob/main/solution/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/Solution.java
This post is licensed under CC BY 4.0 by the author.

