- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 55 lines of Java from the credited upstream file 742.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
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 int findClosestLeaf(TreeNode root, int k) {3 ans = -1;4 minDist = 1000;5 6 Map<TreeNode, Integer> nodeToDist = new HashMap<>();7 8 getDists(root, k, nodeToDist);9 getClosestLeaf(root, 0, nodeToDist);10 11 return ans;12 }13 14 private int ans;15 private int minDist;16 17 private void getDists(TreeNode root, int k, Map<TreeNode, Integer> nodeToDist) {18 if (root == null)19 return;20 if (root.val == k) {21 nodeToDist.put(root, 0);22 return;23 }24 25 getDists(root.left, k, nodeToDist);26 if (nodeToDist.containsKey(root.left)) {27 28 nodeToDist.put(root, nodeToDist.get(root.left) + 1);29 return;30 }31 32 getDists(root.right, k, nodeToDist);33 if (nodeToDist.containsKey(root.right))34 35 nodeToDist.put(root, nodeToDist.get(root.right) + 1);36 }37 38 private void getClosestLeaf(TreeNode root, int dist, Map<TreeNode, Integer> nodeToDist) {39 if (root == null)40 return;41 if (nodeToDist.containsKey(root))42 dist = nodeToDist.get(root);43 if (root.left == null && root.right == null) {44 if (dist < minDist) {45 minDist = dist;46 ans = root.val;47 }48 return;49 }50 51 getClosestLeaf(root.left, dist + 1, nodeToDist);52 getClosestLeaf(root.right, dist + 1, nodeToDist);53 }54}55