Java neat and clear in-order solution


  • 0
    X
    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) {
              list.add(node.val);
            } else if (Math.abs(list.get(0) - target) > Math.abs(node.val - target)) {
              list.remove(0);
              list.add(node.val);
            }
            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.