Closest Binary Search Tree Value II

Given a non-empty binary search tree and a target value, findkvalues in the BST that are closest to the target.

Note:

  • Given target value is a floating point.

  • You may assume k is always valid, that is: k ≤ total nodes.

  • You are guaranteed to have only one unique set of k values in the BST that are closest to the target.

Example

Input:
 root = [4,2,5,1,3], target = 3.714286, and 
k = 2

    4
   / \
  2   5
 / \
1   3

Output:
 [4,3]

Note

直接做法是转化成有序数组,然后用双指针

高级做法是直接在树上双指针:

最优算法,时间复杂度O(k + logn)O(k+logn),空间复杂度O(logn)O(logn)

实现如下的子函数:

  1. getStack() => 在假装插入 target 的时候,看看一路走过的节点都是哪些,放到 stack 里,用于 iterate

  2. moveUpper(stack) => 根据 stack,挪动到 next node

  3. moveLower(stack) => 根据 stack, 挪动到 prev node

有了这些函数之后,就可以把整个树当作一个数组一样来处理,只不过每次 i++ 的时候要用 moveUpper,i--的时候要用 moveLower

Code

Last updated