Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 02fc1ad

Browse files
aQuaaQua
aQua
authored and
aQua
committed
671 finish
1 parent 05bbc6e commit 02fc1ad

File tree

2 files changed

+20
-28
lines changed

2 files changed

+20
-28
lines changed

Algorithms/0671.second-minimum-node-in-a-binary-tree/second-minimum-node-in-a-binary-tree.go

+17-25
Original file line numberDiff line numberDiff line change
@@ -6,36 +6,28 @@ import (
66

77
type TreeNode = kit.TreeNode
88

9-
func findSecondMinimumValue(root *TreeNode) int {
10-
if root == nil ||
11-
root.Left == nil {
12-
return -1
13-
}
9+
const intMax = 1<<63 - 1
1410

15-
if root.Val == root.Left.Val && root.Val == root.Right.Val {
16-
return min(findSecondMinimumValue(root.Left),findSecondMinimumValue(root.Right))
17-
}
11+
func findSecondMinimumValue(root *TreeNode) int {
12+
res := intMax
1813

19-
if root.Left.Val > root.Right.Val {
20-
return helper(root.Left, root.Right)
21-
}
22-
return helper(root.Right, root.Left)
23-
}
14+
helper(root, root.Val, &res)
2415

25-
func helper(l,s *TreeNode) int {
26-
lv := l.Val
27-
sv := findSecondMinimumValue(s)
28-
if sv ==-1 {
29-
return lv
16+
if res == intMax {
17+
return -1
18+
}
19+
return res
3020
}
3121

32-
return min(lv,sv)
33-
}
22+
func helper(root *TreeNode, lo int, hi *int) {
23+
if root == nil {
24+
return
25+
}
3426

35-
func min(a, b int) int {
36-
if a < b {
37-
return a
27+
if lo < root.Val && root.Val < *hi {
28+
*hi = root.Val
3829
}
39-
return b
40-
}
4130

31+
helper(root.Left, lo, hi)
32+
helper(root.Right, lo, hi)
33+
}

Algorithms/0671.second-minimum-node-in-a-binary-tree/second-minimum-node-in-a-binary-tree_test.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ var tcs = []struct {
2222
},
2323

2424
{
25-
[]int{2, 2, 5, 5, 7},
26-
[]int{2, 5, 7, 5, 2},
27-
5,
25+
[]int{4, 2, 5, 1, 6, 3, 7},
26+
[]int{4, 5, 2, 6, 7, 3, 1},
27+
2,
2828
},
2929

3030
// 可以有多个 testcase

0 commit comments

Comments
 (0)