-
Notifications
You must be signed in to change notification settings - Fork 17
/
GetMinimumDifference.kt
72 lines (54 loc) · 1.47 KB
/
GetMinimumDifference.kt
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
63
64
65
66
67
68
69
70
71
72
package com.daily.algothrim.leetcode.top150
import com.daily.algothrim.leetcode.TreeNode
import kotlin.math.min
/**
* 530. 二叉搜索树的最小绝对差
*/
/*
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
示例 1:
输入:root = [4,2,6,1,3]
输出:1
示例 2:
输入:root = [1,0,48,null,null,12,49]
输出:1
提示:
树中节点的数目范围是 [2, 104]
0 <= Node.val <= 105
*/
class GetMinimumDifference {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(GetMinimumDifference().getMinimumDifference(TreeNode(4).apply {
left = TreeNode(2).apply {
left = TreeNode(1)
right = TreeNode(3)
}
right = TreeNode(6)
}))
}
}
private var minResult = Int.MAX_VALUE
private var pre = -1
fun getMinimumDifference(root: TreeNode?): Int {
inOrderTraversal(root)
return minResult
}
/**
* O(n)
* O(n)
*/
private fun inOrderTraversal(root: TreeNode?) {
if (root == null) return
inOrderTraversal(root.left)
if (pre == -1) {
pre = root.`val`
} else {
minResult = min(minResult, root.`val` - pre)
pre = root.`val`
}
inOrderTraversal(root.right)
}
}