package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// 2476. 二叉搜索树最近节点查询
//思路先用中序遍历 左中右获取有序数组,在用二分法寻找最大,最小值
func closestNodes(root *TreeNode, queries []int) [][]int {
res := make([][]int, 0)
m1 := make([]int, 0)
//中序遍历获取有序数组
var searchBST func(node *TreeNode)
searchBST = func(node *TreeNode) {
if node == nil {
return
}
searchBST(node.Left)
m1 = append(m1, node.Val)
searchBST(node.Right)
}
searchBST(root)
for _, v := range queries {
res = append(res, []int{findMinVal(m1, v), findMaxVal(m1, v)})
}
return res
}
//求最小值
func findMinVal(nums []int, n int) int {
left := 0
right := len(nums) - 1
if n < nums[left] {
return -1
}
for left < right {
mid := (left + right) / 2
if nums[mid] == n {
return nums[mid]
} else if nums[mid] < n {
if mid+1 == len(nums) || nums[mid+1] > n {
return nums[mid]
}
left = mid + 1
} else {
right = mid - 1
}
}
return nums[left]
}
//求最大值
func findMaxVal(nums []int, n int) int {
left := 0
right := len(nums) - 1
if n > nums[right] {
return -1
}
for left < right {
mid := (left + right) / 2
if nums[mid] == n {
return nums[mid]
} else if nums[mid] > n {
if mid-1 < 0 || nums[mid-1] < n {
return nums[mid]
}
right = mid - 1
} else {
left = mid + 1
}
}
return nums[right]
}