Created
June 14, 2019 14:54
-
-
Save Hunachi/f479f8bce6fcb2172184adfbf587645f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include<math.h> | |
using namespace std; | |
struct node { | |
long value = 0; | |
node *right = nullptr; | |
node *left = nullptr; | |
}; | |
struct tree { | |
node *root = nullptr; | |
}; | |
void insert(node *root, node *node1) { | |
if (root->value > node1->value) { | |
if (root->left == nullptr) { | |
//cout << node1->value << " in" << endl; | |
root->left = node1; | |
} else { | |
//cout << node1->value << " right" << endl; | |
insert(root->left, node1); | |
} | |
} else { | |
if (root->right == nullptr) { | |
//cout << node1->value << " in" << endl; | |
root->right = node1; | |
} else { | |
//cout << node1->value << " left" << endl; | |
insert(root->right, node1); | |
} | |
} | |
} | |
void insert_tree(tree *tree1) { | |
long in_key; | |
cin >> in_key; | |
node *node1 = (node *) malloc(sizeof(node)); | |
node1->value = in_key; | |
if (tree1->root == nullptr) { | |
tree1->root = node1; | |
} else { | |
insert(tree1->root, node1); | |
} | |
} | |
void print_tree_mid(node *node1) { | |
if(node1->left != nullptr)print_tree_mid(node1->left); | |
cout << " " << node1->value; | |
if(node1->right != nullptr)print_tree_mid(node1->right); | |
} | |
void print_tree_pre(node *node1) { | |
cout << " " << node1->value; | |
if(node1->left != nullptr)print_tree_pre(node1->left); | |
if(node1->right != nullptr)print_tree_pre(node1->right); | |
} | |
void print_tree(tree *tree1){ | |
print_tree_mid(tree1->root); | |
cout << endl; | |
print_tree_pre(tree1->root); | |
cout << endl; | |
} | |
int main() { | |
long m; | |
string PRINT = "print", INSERT = "insert", s; | |
cin >> m; | |
tree *tree1 = (struct tree *) malloc(sizeof(tree)); | |
for (int i = 0; i < m; i++) { | |
cin >> s; | |
if (s == INSERT) insert_tree(tree1); | |
else print_tree(tree1); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment