题目链接:
题解
题目中有坑,如果树退化成一个链,每次在树上搜索会超时。所以先把二叉搜索树转到一个数组(中序遍历),然后每次在数组上二分查找。
参考代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
class Solution { public: vector<vector<int>> closestNodes(TreeNode* root, vector<int>& queries) { vector<int> tmp; queue<TreeNode*> q; q.push(root); while(!q.empty()) { TreeNode* node = q.front(); q.pop(); tmp.push_back(node->val); if(node->left) q.push(node->left); if(node->right) q.push(node->right); }
sort(tmp.begin(), tmp.end()); vector<vector<int>> ans; for(int i = 0; i < queries.size(); i++) { int left = -1; int right = -1; int k = lower_bound(tmp.begin(), tmp.end(), queries[i]) - tmp.begin(); if(k!=tmp.size() && tmp[k] == queries[i]) { left = queries[i]; right = queries[i]; } else if (k == 0) {right = tmp[k];} else if (k == tmp.size()) {left = tmp[k-1];} else { left = tmp[k-1]; right = tmp[k]; }
ans.push_back({left, right}); } return ans; } };
|