-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmin_abs_dff_bst.go
62 lines (55 loc) · 1.14 KB
/
min_abs_dff_bst.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
54
55
56
57
58
59
60
61
62
package problem0530
import (
. "leetcodedaily/helpers/binarytree"
"math"
)
/*
Given the root of a Binary Search Tree (BST),
return the minimum absolute difference between the values of any two different nodes in the tree.
*/
func getMinimumDifferencePointers(root *TreeNode) int {
var res, prev int = math.MaxInt, math.MaxInt
helperWithPointers(root, &prev, &res)
return res
}
func helperWithPointers(root *TreeNode, prev, min *int) {
if root == nil {
return
}
helperWithPointers(root.Left, prev, min)
*min = minWithAbs((root.Val - *prev), *min)
*prev = root.Val
helperWithPointers(root.Right, prev, min)
}
func getMinimumDifferenceChan(root *TreeNode) int {
var res, prev int = math.MaxInt, math.MaxInt
var ch = make(chan int)
go func() {
helperWithChans(root, ch)
close(ch)
}()
for cur := range ch {
res = minWithAbs(prev-cur, res)
prev = cur
}
return res
}
func helperWithChans(root *TreeNode, ch chan int) {
if root != nil {
helperWithChans(root.Left, ch)
ch <- root.Val
helperWithChans(root.Right, ch)
}
}
func minWithAbs(a, b int) int {
if a < 0 {
a = -a
}
if b < 0 {
b = -b
}
if a < b {
return a
}
return b
}