- 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
- 57 lines of C++ from the credited upstream file 742.cpp.
- The implementation visibly relies on hash 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:3 int findClosestLeaf(TreeNode* root, int k) {4 int ans = -1;5 int minDist = 1000;6 7 unordered_map<TreeNode*, int> nodeToDist;8 9 getDists(root, k, nodeToDist);10 getClosestLeaf(root, 0, nodeToDist, minDist, ans);11 12 return ans;13 }14 15 private:16 void getDists(TreeNode* root, int k,17 unordered_map<TreeNode*, int>& nodeToDist) {18 if (root == nullptr)19 return;20 if (root->val == k) {21 nodeToDist[root] = 0;22 return;23 }24 25 getDists(root->left, k, nodeToDist);26 if (const auto it = nodeToDist.find(root->left); it != nodeToDist.cend()) {27 28 nodeToDist[root] = it->second + 1;29 return;30 }31 32 getDists(root->right, k, nodeToDist);33 if (const auto it = nodeToDist.find(root->right); it != nodeToDist.cend())34 35 nodeToDist[root] = it->second + 1;36 }37 38 void getClosestLeaf(TreeNode* root, int dist,39 unordered_map<TreeNode*, int>& nodeToDist, int& minDist,40 int& ans) {41 if (root == nullptr)42 return;43 if (nodeToDist.contains(root))44 dist = nodeToDist[root];45 if (root->left == nullptr && root->right == nullptr) {46 if (dist < minDist) {47 minDist = dist;48 ans = root->val;49 }50 return;51 }52 53 getClosestLeaf(root->left, dist + 1, nodeToDist, minDist, ans);54 getClosestLeaf(root->right, dist + 1, nodeToDist, minDist, ans);55 }56};57