class Solution {
List<Integer> sort = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> closestNodes(TreeNode root, List<Integer> q) {
dfs(root);
for (int x : q) {
int idx = search(x), a = -1, b = -1, c = sort.get(idx);
if (c == x) {a = b = sort.get(idx);}
if (c > x && idx != 0) {a = sort.get(idx - 1); b = c;}
else if(c > x && idx == 0) b = c;
else a = c;
ans.add(Arrays.asList(a, b));
}
return ans;
}
int search(int x) { //寻找大于等于的元素下标
int l = 0, r = sort.size() - 1;
while (l < r) {
int mid = (l + r) / 2;
if (sort.get(mid) >= x) r = mid;
else l = mid + 1;
}
return r;
}
void dfs(TreeNode root) {
if (root == null) return;
dfs(root.left);
sort.add(root.val);
dfs(root.right);
}
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func closestNodes(root *TreeNode, queries []int) [][]int {
a := []int{}
var dfs func(*TreeNode)
dfs = func(o *TreeNode) {
if o == nil {
return
}
dfs(o.Left)
a = append(a, o.Val)
dfs(o.Right)
}
dfs(root)
ans := make([][]int, len(queries))
for i, q := range queries {
min, max := -1, -1
// 这是怎么转换的,可以看我上面贴的视频链接
j := sort.SearchInts(a, q+1) - 1
if j >= 0 {
min = a[j]
}
j = sort.SearchInts(a, q)
if j < len(a) {
max = a[j]
}
ans[i] = []int{min, max}
}
return ans
}
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# 中序遍历 + 二分查找
class Solution:
def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]:
a = []
def dfs(o: Optional[TreeNode]) -> None:
if o is None: return
dfs(o.left)
a.append(o.val)
dfs(o.right)
dfs(root)
ans = []
for q in queries:
j = bisect_right(a, q)
min = a[j - 1] if j else -1
j = bisect_left(a, q)
max = a[j] if j < len(a) else -1
ans.append([min, max])
return ans