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
|
type Result struct {
diff int
minVal int
maxVal int
}
func getMinimumDifference(root *TreeNode) int {
if root == nil {
return 0
}
var dfs func(root *TreeNode) *Result
dfs = func(root *TreeNode) *Result {
ret := &Result{}
if root.Left == nil && root.Right == nil {
// note: assign ret.diff to math.MaxInt32
ret.diff, ret.minVal, ret.maxVal = math.MaxInt32, root.Val, root.Val
} else if root.Left == nil {
// root.Right != nil
rightRes := dfs(root.Right)
curDiff := min(rightRes.minVal-root.Val, rightRes.diff)
ret.diff, ret.minVal, ret.maxVal = curDiff, root.Val, rightRes.maxVal
} else if root.Right == nil {
// root.Left != nil
leftRes := dfs(root.Left)
curDiff := min(root.Val-leftRes.maxVal, leftRes.diff)
ret.diff, ret.minVal, ret.maxVal = curDiff, leftRes.minVal, root.Val
} else {
// root.Left != nil && root.Right != nil
leftRes := dfs(root.Left)
rightRes := dfs(root.Right)
curDiff := min(root.Val-leftRes.maxVal, rightRes.minVal-root.Val, leftRes.diff, rightRes.diff)
ret.diff, ret.minVal, ret.maxVal = curDiff, leftRes.minVal, rightRes.maxVal
}
return ret
}
return dfs(root).diff
}
func min(nums ...int) int {
ret := nums[0]
for _, num := range nums {
if num < ret {
ret = num
}
}
return ret
}
|