- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 36 lines of Java from the credited upstream file 2476.java.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public List<List<Integer>> closestNodes(TreeNode root, List<Integer> queries) {3 List<List<Integer>> ans = new ArrayList<>();4 List<Integer> sortedVals = new ArrayList<>();5 6 inorder(root, sortedVals);7 8 for (final int query : queries) {9 final int i = firstGreaterEqual(sortedVals, query);10 11 if (i != sortedVals.size() && sortedVals.get(i) == query)12 ans.add(Arrays.asList(query, query));13 14 else15 ans.add(Arrays.asList(i == 0 ? -1 : sortedVals.get(i - 1),16 i == sortedVals.size() ? -1 : sortedVals.get(i)));17 }18 19 return ans;20 }21 22 23 private void inorder(TreeNode root, List<Integer> sortedVals) {24 if (root == null)25 return;26 inorder(root.left, sortedVals);27 sortedVals.add(root.val);28 inorder(root.right, sortedVals);29 }30 31 private int firstGreaterEqual(List<Integer> A, int target) {32 final int i = Collections.binarySearch(A, target);33 return i < 0 ? -i - 1 : i;34 }35}36