Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
63 lines (61 loc) · 1.71 KB

File metadata and controls

63 lines (61 loc) · 1.71 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
55
56
57
58
59
60
61
62
63
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class IterativeSolution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
List<TreeNode> curr = new ArrayList<TreeNode>();
curr.add(root);
int depth = 1;
while (curr.isEmpty() == false) {
List<TreeNode> next = new ArrayList<TreeNode>();
for(int i = 0; i < curr.size(); i++) {
if (curr.get(i).left == null && curr.get(i).right == null) {
return depth;
}
if (curr.get(i).left != null) {
next.add(curr.get(i).left);
}
if (curr.get(i).right != null) {
next.add(curr.get(i).right);
}
}
depth += 1;
curr.clear();
curr = next;
}
return depth;
}
}
public class RecursiveSolution {
public int minDepth(TreeNode root) {
int depth = 0;
if (root == null) {
return depth;
} else {
return check(root, depth+1);
}
}
public int check(TreeNode root, int depth) {
if (root.left == null && root.right == null) {
return depth;
}
else if (root.left != null && root.right != null) {
return Math.min(check(root.left, depth+1), check(root.right, depth+1));
}
else if (root.left != null) {
return check(root.left, depth + 1);
}
else {
return check(root.right, depth + 1);
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.