Skip to content

Commit 8b77f01

Browse files
committed
Solved a binary tree problem
1 parent 4b4194a commit 8b77f01

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
class Solution {
11+
public int findSecondMinimumValue(TreeNode root) {
12+
if (root == null) {
13+
return -1;
14+
}
15+
if (root.left == null && root.right == null) {
16+
return -1;
17+
}
18+
19+
int left = root.left.val;
20+
int right = root.right.val;
21+
22+
// if value same as root value, need to find the next candidate
23+
if (root.left.val == root.val) {
24+
left = findSecondMinimumValue(root.left);
25+
}
26+
if (root.right.val == root.val) {
27+
right = findSecondMinimumValue(root.right);
28+
}
29+
30+
if (left != -1 && right != -1) {
31+
return Math.min(left, right);
32+
} else if (left != -1) {
33+
return left;
34+
} else {
35+
return right;
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)