O(n) inorder traversal solution.


  • 0
    H

    Keep k length result window. Trim results during traversal. Stop when we start moving away from target.

    public class Solution {
    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        int closest = root.val;
        TreeNode closestNode = root;
        TreeNode cur = root;
        Stack<TreeNode> stack = new Stack<>();
        LinkedList<Integer> res = new LinkedList<>();
        while (!stack.empty() || cur != null) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                res.add(cur.val);
                cur = cur.right;
                boolean stop = trim(res, target, k);
                if (stop) break;
            }
        }
        return res;
    }
    private boolean trim(LinkedList<Integer> res, double target, int k) {
        if (res.size() <= k) return false;
        double right = Math.abs(res.get(res.size() - 1) - target);
        double left = Math.abs(res.get(0) - target);
        if (right < left) { // move torwards target
            res.removeFirst();
            return false;
        } else {
            res.removeLast(); // move away from target
            return true;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.