-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path230_kth_smallest_test.go
55 lines (49 loc) · 1.04 KB
/
230_kth_smallest_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
54
55
package _5_binary_tree
import (
"github.com/smartystreets/goconvey/convey"
"testing"
)
// 二叉搜索树中第K小的元素 https://leetcode.cn/problems/kth-smallest-element-in-a-bst/description/
func TestKthSmallest(t *testing.T) {
convey.Convey("二叉搜索树中第K小的元素:中序遍历", t, func() {
testCase := []struct {
input *TreeNode
k int
target int
}{
{
Ints2TreeNode([]int{3, 1, 4, NULL, 2}),
1,
1,
},
{
Ints2TreeNode([]int{5, 3, 6, 2, 4, NULL, NULL, 1}),
3,
3,
},
}
for _, tst := range testCase {
rsp := kthSmallest(tst.input, tst.k)
convey.So(rsp, convey.ShouldEqual, tst.target)
}
})
}
func kthSmallest(root *TreeNode, k int) int {
// 94. 二叉树的中序遍历
stack := []*TreeNode{root}
for root != nil || len(stack) > 0 {
for root != nil {
stack = append(stack, root)
root = root.Left
}
root = stack[len(stack)-1]
stack = stack[:len(stack)-1]
// 开始记录答案
k--
if k == 0 {
return root.Val
}
root = root.Right
}
return 0
}