Java neat and clear in-order solution

  • 0
    public class Solution {
        public List<Integer> closestKValues(TreeNode root, double target, int k) {
            List<Integer> res = new ArrayList<>();
            preorder(root, res, target, k);
            return res;
        public void preorder(TreeNode node, List<Integer> list, double target, int k) {
            if (node == null) { return; }
            preorder(node.left, list, target, k);
            if (list.size() < k) {
            } else if (Math.abs(list.get(0) - target) > Math.abs(node.val - target)) {
            preorder(node.right, list, target, k);

Log in to reply

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