/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ publicclassSolution{ public List<Integer> closestKValues(TreeNode root, double target, int k){ Queue<Integer> result = new LinkedList<>(); Stack<TreeNode> stack = new Stack<>(); while (root != null) { stack.push(root); root = root.left; }
while (!stack.isEmpty()) { TreeNode node = stack.pop(); if (result.size() < k) { result.offer(node.val); } else { int first = result.peek(); if (Math.abs(first - target) > Math.abs(node.val - target)) { result.poll(); result.offer(node.val); } else { break; } }
if (node.right != null) { TreeNode right = node.right; while (right != null) { stack.add(right); right = right.left; } } }