Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- struct Node{
- Node *lhs;
- Node *rhs;
- int val;
- Node(int v) : val(v){
- rhs = nullptr;
- lhs = nullptr;
- }
- };
- class BinaryTree{
- public:
- BinaryTree();
- BinaryTree(std::vector<bool> v);
- void push(int val);
- bool empty();
- int top() const;
- size_t Size() const;
- void print(Node* p);
- void printFromHead();
- BinaryTree& operator=(const BinaryTree& rhs){
- Node* tmp = rhs.head;
- return copy(tmp);
- }
- private:
- size_t size;
- Node *head;
- BinaryTree& copy(Node* rhs);
- };
- BinaryTree& BinaryTree::copy(Node* rhs){
- if(rhs == nullptr){
- return *this;
- }
- copy(rhs->rhs);
- copy(rhs->lhs);
- push(rhs->val);
- }
- BinaryTree::BinaryTree() {
- head = nullptr;
- size = 0;
- }
- BinaryTree::BinaryTree(std::vector<bool> v){
- for (int i = 0; i < v.size(); ++i) {
- push(v[i]);
- }
- }
- void BinaryTree::print(Node* p){
- std::cout << p->val << '\n';
- if(p->lhs != nullptr){
- print(p->lhs);
- }
- if(p->rhs != nullptr){
- print(p->rhs);
- }
- }
- void BinaryTree::printFromHead() {
- print(head);
- }
- void BinaryTree::push(int val){
- Node *tmp = new Node(val);
- if(head != nullptr){
- Node *last = head;
- while(last->lhs != nullptr || last->rhs != nullptr){
- if(last->rhs != nullptr){
- last = last->rhs;
- }else if(last->lhs != nullptr){
- last = last->lhs;
- }else{
- break;
- }
- }
- if(last->val >= val){
- last->lhs = tmp;
- }else{
- last->rhs = tmp;
- }
- }else{
- head = new Node(val);
- }
- size++;
- }
- bool BinaryTree::empty(){
- return head == nullptr;
- }
- size_t BinaryTree::Size() const{
- return size;
- }
- int BinaryTree::top() const{
- return head->val;
- }
- int main() {
- std::cout << "First tree:\n";
- BinaryTree *bt = new BinaryTree();
- bt->push(12);
- bt->push(10);
- bt->push(111);
- bt->push(150);
- std::cout << bt->empty() << '\n';
- std::cout << bt->Size() << '\n';
- bt->printFromHead();
- std::cout << "Second, bitmask tree:\n";
- std::vector<bool> v = {1,0,1,0};
- BinaryTree bt2 = BinaryTree(v);
- bt2.printFromHead();
- std::cout << "Third tree\n";
- BinaryTree bt3 = bt2;
- bt3.printFromHead();
- }
Add Comment
Please, Sign In to add comment