2476. 二叉搜索树最近节点查询

二叉搜索树最近节点查询

解法一: 中序遍历,二分查找

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
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func closestNodes(root *TreeNode, queries []int) [][]int {
list := []int{}
dfs(root, &list)
ans := make([][]int, len(queries))
for i, query := range queries {
ans[i] = []int{halfSearchMax(list, query), halfSearchMin(list, query)}
}
return ans
}

func dfs(node *TreeNode, list *[]int) {
if node == nil {
return
}
dfs(node.Left, list)
*list = append(*list, node.Val)
dfs(node.Right, list)
}

func halfSearchMax(list []int, target int) int {
left := 0
right := len(list) - 1
for left <= right {
mid := ((right - left) >> 1) + left
if list[mid] <= target {
left = mid + 1
} else {
right = mid - 1
}
}
if right < 0 {
return -1
}
return list[right]
}

func halfSearchMin(list []int, target int) int {
left := 0
right := len(list) - 1
for left <= right {
mid := ((right - left) >> 1) + left
if list[mid] >= target {
right = mid - 1
} else {
left = mid + 1
}
}
if left >= len(list) {
return -1
}
return list[left]
}
作者

wuhunyu

发布于

2024-02-24

更新于

2025-01-15

许可协议