Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
closest-binary-search-tree-value-ii.cpp 2.55 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2015-09-16 23:37 +08:00 . Update closest-binary-search-tree-value-ii.cpp
// Time: O(h + k)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {
// The forward or backward iterator.
const auto backward = [](const vector<TreeNode*>& s) { return s.back()->left; };
const auto forward = [](const vector<TreeNode*>& s) { return s.back()->right; };
const auto closest = [&target](const TreeNode* a, const TreeNode* b) {
return abs(a->val - target) < abs(b->val - target);
};
// Build the stack to the closest node.
vector<TreeNode*> s;
while (root) {
s.emplace_back(root);
root = target < root->val ? root->left : root->right;
}
// Get the stack to the next smaller node.
vector<TreeNode*> forward_stack(s.cbegin(), next(min_element(s.cbegin(), s.cend(), closest)));
vector<TreeNode*> backward_stack(forward_stack);
nextNode(backward_stack, backward, forward);
// Get the closest k values by advancing the iterators of the stacks.
vector<int> result;
for (int i = 0; i < k; ++i) {
if (!forward_stack.empty() &&
(backward_stack.empty() || closest(forward_stack.back(), backward_stack.back()))) {
result.emplace_back(forward_stack.back()->val);
nextNode(forward_stack, forward, backward);
} else if (!backward_stack.empty() &&
(forward_stack.empty() || !closest(forward_stack.back(), backward_stack.back()))) {
result.emplace_back(backward_stack.back()->val);
nextNode(backward_stack, backward, forward);
}
}
return result;
}
// Helper to make a stack to the next node.
template<typename T, typename U>
void nextNode(vector<TreeNode*>& s, const T& child1, const U& child2) {
if (!s.empty()) {
if (child2(s)) {
s.emplace_back(child2(s));
while (child1(s)) {
s.emplace_back(child1(s));
}
} else {
auto child = s.back();
s.pop_back();
while (!s.empty() && child == child2(s)) {
child = s.back();
s.pop_back();
}
}
}
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助