272. Closest Binary Search Tree Value II

题目链接:https://leetcode.com/problems...

bst的值大小顺序实际上就是满足inorder的条件,所以直接中序遍历,过程中维护一个queue,放入k个当前离target最近的值,queue的size=k时,新的值和target的距离如果小于队首的那个值和target的距离那么移除队首,如果size=k,且新的距离大于等于队首的距离,直接退出,返回队列中的所有结果。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        Queue<Integer> q = new LinkedList();
        TreeNode prev = null, cur = root;
        while(cur != null) {
            if(cur.left == null) {
                if(q.size() == k) {
                    if(Math.abs(q.peek() - target) <= Math.abs(cur.val - target)) break;
                    q.poll();
                }
                q.offer(cur.val);
                cur = cur.right;
            }
            else {
                prev = cur.left;
                while(prev.right != cur && prev.right != null) prev = prev.right;
                // connect the prev with current
                if(prev.right == null) {
                    prev.right = cur;
                    cur = cur.left;
                }
                // traverse to current node
                else {
                    prev.right = null;
                    if(q.size() == k) {
                        if(Math.abs(q.peek() - target) <= Math.abs(cur.val - target)) break;
                        q.poll();
                    }
                    q.offer(cur.val);
                    cur = cur.right;
                }
                
            }
        }
        
        return (List) q;
    }
}

按要求是要O(h)的时间复杂度。提示找pre和suc,那么分别找到离k最近的pre和suc就好了,bst里面找离最近的k的复杂度是O(h),这个过程中要把路上的node存下来,以便找pre和next。
参考discussion里的:
https://discuss.leetcode.com/...


lulouch13
13 声望6 粉丝