Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 7bdd94a

Browse files
authored
Update Second Minimum Node in a binary tree.java
1 parent 4c1b04b commit 7bdd94a

File tree

1 file changed

+10
-14
lines changed

1 file changed

+10
-14
lines changed

Easy/Second Minimum Node in a binary tree.java

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,26 +13,22 @@
1313
* }
1414
* }
1515
*/
16-
class Solution {
17-
Integer minimum;
18-
long secondMinimum;
16+
class Solution {
1917
public int findSecondMinimumValue(TreeNode root) {
20-
minimum = root.val;
21-
secondMinimum = Long.MAX_VALUE;
22-
helper(root);
23-
return secondMinimum == Long.MAX_VALUE ? -1 : (int) secondMinimum;
18+
long[] topTwo = {root.val, Long.MAX_VALUE};
19+
helper(root, topTwo);
20+
return topTwo[1] == Long.MAX_VALUE ? -1 : (int) topTwo[1];
2421
}
2522

26-
private void helper(TreeNode root) {
23+
private void helper(TreeNode root, long[] topTwo) {
2724
if (root == null) {
2825
return;
2926
}
30-
if (minimum < root.val && root.val < secondMinimum) {
31-
secondMinimum = root.val;
32-
}
33-
else if (root.val == minimum) {
34-
helper(root.left);
35-
helper(root.right);
27+
if (topTwo[0] < root.val && root.val < topTwo[1]) {
28+
topTwo[1] = root.val;
29+
} else {
30+
helper(root.left, topTwo);
31+
helper(root.right, topTwo);
3632
}
3733
}
3834
}

0 commit comments

Comments
 (0)