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

Sign up
Appearance settings

Commit bfe620a

Browse files
Add Solution.java to problems 0111
1 parent cc40f19 commit bfe620a

File tree

2 files changed

+60
-7
lines changed

2 files changed

+60
-7
lines changed
Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,22 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
110
class Solution {
211
public int minDepth(TreeNode root) {
3-
if(root == null) return 0;
4-
if(root.left==null && root.right==null) return 1;
5-
int leftDepth = minDepth(root.left);
6-
if(leftDepth==0) leftDepth = Integer.MAX_VALUE;
7-
int rightDepth = minDepth(root.right);
8-
if(rightDepth==0) rightDepth = Integer.MAX_VALUE;
9-
return Math.min(leftDepth,rightDepth)+1;
12+
if (root == null) return 0;
13+
14+
if (root.left == null && root.right != null) {
15+
return 1 + minDepth(root.right);
16+
}
17+
if (root.right == null && root.left != null) {
18+
return 1 + minDepth(root.left);
19+
}
20+
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
1021
}
1122
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
11+
class Pair {
12+
TreeNode node;
13+
Integer height;
14+
public Pair(TreeNode node, Integer height) {
15+
this.node = node;
16+
this.height = height;
17+
}
18+
}
19+
20+
class Solution {
21+
public int minDepth(TreeNode root) {
22+
if (root == null) return 0;
23+
24+
Stack<Pair> stack = new Stack<>();
25+
stack.push(new Pair(root, 1));
26+
27+
int res = Integer.MAX_VALUE;
28+
while (!stack.isEmpty()) {
29+
Pair pair = stack.pop();
30+
if (pair.node.left == null && pair.node.right == null) {
31+
res = Math.min(pair.height, res);
32+
}
33+
if (pair.node.left != null){
34+
stack.push(new Pair(pair.node.left, pair.height + 1));
35+
}
36+
if (pair.node.right != null) {
37+
stack.push(new Pair(pair.node.right, pair.height + 1));
38+
}
39+
}
40+
return res;
41+
}
42+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /