-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathFind_k_largest_BST.cpp
70 lines (63 loc) · 2.04 KB
/
Find_k_largest_BST.cpp
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
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#include <cassert>
#include <iostream>
#include <memory>
#include <random>
#include <vector>
#include "./BST_prototype.h"
using std::cout;
using std::default_random_engine;
using std::endl;
using std::random_device;
using std::uniform_int_distribution;
using std::unique_ptr;
using std::vector;
void find_k_largest_in_BST_helper(const unique_ptr<BSTNode<int>>& r, int k,
vector<int>* k_elements);
// @include
vector<int> find_k_largest_in_BST(const unique_ptr<BSTNode<int>>& root,
int k) {
vector<int> k_elements;
find_k_largest_in_BST_helper(root, k, &k_elements);
return k_elements;
}
void find_k_largest_in_BST_helper(const unique_ptr<BSTNode<int>>& r, int k,
vector<int>* k_elements) {
// Performs reverse inorder traversal.
if (r && k_elements->size() < k) {
find_k_largest_in_BST_helper(r->right, k, k_elements);
if (k_elements->size() < k) {
k_elements->emplace_back(r->data);
find_k_largest_in_BST_helper(r->left, k, k_elements);
}
}
}
// @exclude
int main(int argc, char* argv[]) {
// 3
// 2 5
// 1 4 6
unique_ptr<BSTNode<int>> root = unique_ptr<BSTNode<int>>(new BSTNode<int>{3});
root->left = unique_ptr<BSTNode<int>>(new BSTNode<int>{2});
root->left->left = unique_ptr<BSTNode<int>>(new BSTNode<int>{1});
root->right = unique_ptr<BSTNode<int>>(new BSTNode<int>{5});
root->right->left = unique_ptr<BSTNode<int>>(new BSTNode<int>{4});
root->right->right = unique_ptr<BSTNode<int>>(new BSTNode<int>{6});
default_random_engine gen((random_device())());
int k;
if (argc == 2) {
k = atoi(argv[1]);
} else {
uniform_int_distribution<int> dis(1, 6);
k = dis(gen);
}
cout << "k = " << k << endl;
vector<int> ans = find_k_largest_in_BST(root, k);
for (int i = 0; i < ans.size(); ++i) {
cout << ans[i] << endl;
}
for (int i = 1; i < ans.size(); ++i) {
assert(ans[i - 1] >= ans[i]);
}
return 0;
}