-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_minimum_difference_test.go
53 lines (43 loc) · 1.02 KB
/
get_minimum_difference_test.go
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
// https://leetcode.com/problems/minimum-absolute-difference-in-bst
package problems
import (
"math"
"testing"
"github.com/dobermanch/leetcode/core"
)
type GetMinimumDifference struct{}
func TestGetMinimumDifference(t *testing.T) {
gen := core.TestSuite[GetMinimumDifference]{}
gen.Add(func(tc *core.TestCase) {
root := &TreeNode{
Val: 10,
Left: &TreeNode{Val: 0, Left: &TreeNode{Val: 4}},
Right: &TreeNode{Val: 48, Left: &TreeNode{Val: 16}, Right: &TreeNode{Val: 56}},
}
tc.Param(root).Result(6)
}).Run(t)
}
func (GetMinimumDifference) Solution(root *TreeNode) int {
stack := []*TreeNode{}
diff := math.MaxInt
node := root
var prevNode *TreeNode
for node != nil || len(stack) > 0 {
if node != nil {
stack = append(stack, node)
node = node.Left
} else {
pop := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if prevNode != nil {
newDiff := pop.Val - prevNode.Val
if newDiff < diff {
diff = newDiff
}
}
prevNode = pop
node = pop.Right
}
}
return diff
}