-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution2.go
52 lines (49 loc) · 859 Bytes
/
Solution2.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
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type BST struct {
cnt map[*TreeNode]int
root *TreeNode
}
func newBST(root *TreeNode) *BST {
var count func(*TreeNode) int
cnt := map[*TreeNode]int{}
count = func(root *TreeNode) int {
if root == nil {
return 0
}
n := 1 + count(root.Left) + count(root.Right)
cnt[root] = n
return n
}
count(root)
return &BST{cnt, root}
}
func (bst *BST) kthSmallest(k int) int {
node := bst.root
for node != nil {
v := 0
if node.Left != nil {
v = bst.cnt[node.Left]
}
if v == k-1 {
return node.Val
}
if v < k-1 {
k -= (v + 1)
node = node.Right
} else {
node = node.Left
}
}
return 0
}
func kthSmallest(root *TreeNode, k int) int {
bst := newBST(root)
return bst.kthSmallest(k)
}