-
Notifications
You must be signed in to change notification settings - Fork 7
/
Main.java
54 lines (48 loc) · 1.41 KB
/
Main.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.company;
import com.sun.source.tree.Tree;
import java.util.ArrayDeque;
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;
}
}
public class Main {
public static void main(String[] args) {
// write your code here
}
int min = Integer.MAX_VALUE;
public int minDepth_dfs(TreeNode root) {
if(root == null) return 0;
dfs(root, 1);
return min;
}
public void dfs(TreeNode node, int depth){
if(node == null) return;
if(node.left == node.right) min = Math.min(min, depth);
dfs(node.left, depth + 1);
dfs(node.right, depth + 1);
}
public int minDepth_bfs(TreeNode root) {
if(root == null) return 0;
ArrayDeque<TreeNode> queue = new ArrayDeque<>(){{offer(root);}};
int depth = 0;
while (!queue.isEmpty()){
int count = queue.size();
depth++;
for (int i = 0; i < count; i++) {
TreeNode cur = queue.poll();
if(cur.left == cur.right) return depth;
if(cur.left != null) queue.offer(cur.left);
if(cur.right != null) queue.offer(cur.right);
}
}
return -1;
}
}