commit 2 in cpp
This commit is contained in:
1 parent
9e742f0d79
commit
32af7721e0
4 files changed
+275
-1
No files matched your search
@@ -0,0 +1,102 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
int log2int(int n){
|
||||
if (n <= 1){
|
||||
return 0; // no support + n is int anyway
|
||||
}
|
||||
return 1 + log2int(n / 2);
|
||||
}
|
||||
class binary_tree
|
||||
{
|
||||
public:
|
||||
binary_tree() {}
|
||||
void append(int x)
|
||||
{
|
||||
data.push_back(x);
|
||||
maintain_shape(0);
|
||||
}
|
||||
void maintain_shape(int ind)
|
||||
{
|
||||
int left = 2 * ind + 1;
|
||||
int right = 2 * ind + 2; // damn this is accounted for 0 indexing gj ai
|
||||
if (left > data.size())
|
||||
{ // 100% leaf
|
||||
return;
|
||||
}
|
||||
if (right > data.size())
|
||||
{ // only node is left, and that node is also last ele in data
|
||||
if (data[ind] < data[left])
|
||||
{
|
||||
std::swap(data[ind], data[left]); // bigger higher
|
||||
}
|
||||
return;
|
||||
}
|
||||
maintain_shape(left);
|
||||
maintain_shape(right);
|
||||
// ordering? so the last item at index data.size() - 1 isnt swapped last: may lead to problem??? idk
|
||||
if (data[ind] < data[left])
|
||||
std::swap(data[ind], data[left]);
|
||||
if (data[ind] < data[right])
|
||||
std::swap(data[ind], data[right]);
|
||||
}
|
||||
int pop() {
|
||||
int ret = data[0];
|
||||
data[0] = data[data.size() - 1];
|
||||
data.pop_back();
|
||||
maintain_shape(0);
|
||||
return ret;
|
||||
}
|
||||
void add(std::vector<int> add) {
|
||||
for (int i = 0; i < add.size(); i++) {
|
||||
data.push_back(add[i]);
|
||||
}
|
||||
maintain_shape(0);
|
||||
}
|
||||
void print() {
|
||||
// insane sauce:
|
||||
int twos = 0;
|
||||
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
if (log2int(i + 1) == twos + 1) {
|
||||
std::cout << std::endl;
|
||||
twos++;
|
||||
}
|
||||
std::cout << data[i] << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
private:
|
||||
std::vector<int> data;
|
||||
};
|
||||
|
||||
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
binary_tree bt;
|
||||
bt.append(1);
|
||||
bt.append(2);
|
||||
bt.append(6);
|
||||
std::cout << "\n";
|
||||
bt.print();
|
||||
bt.append(4);
|
||||
bt.append(5);
|
||||
std::cout << "\n";
|
||||
bt.print();
|
||||
bt.append(9);
|
||||
std::cout << "\n";
|
||||
bt.print();
|
||||
bt.append(8);
|
||||
std::cout << "\n";
|
||||
bt.print();
|
||||
int popped = bt.pop();
|
||||
std::cout << "popped: " << popped << std::endl;
|
||||
bt.print();
|
||||
popped = bt.pop();
|
||||
std::cout << "popped: " << popped << std::endl;
|
||||
bt.print();
|
||||
bt.add({6,5,11, 8, 10,15,3,7,1,12,4, 9});
|
||||
std::cout << "\n";
|
||||
bt.print();
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user