Created
March 14, 2017 23:38
-
-
Save tooshitaka/75c6237289e9f10b588a26566640136c 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 <algorithm> | |
#include <string> | |
using namespace std; | |
struct node { | |
int key; | |
node* left; | |
node* right; | |
}; | |
node *root = NULL; | |
// Insert new key | |
void insert(int key) | |
{ | |
node *n = new node(); | |
*n = { NULL }; | |
n->key = key; | |
node *x = root; | |
node *y; | |
y = NULL; | |
while (x != NULL) { | |
y = x; | |
if (x->key >= n->key) | |
x = x->left; | |
else | |
x = x->right; | |
} | |
if (y == NULL) | |
root = n; | |
else if (y->key >= n->key) | |
y->left = n; | |
else | |
y->right = n; | |
} | |
// Pre-order traversal | |
void preorder(node* n) | |
{ | |
cout << " " << n->key; | |
if(n->left != NULL) | |
preorder(n->left); | |
if (n->right != NULL) | |
preorder(n->right); | |
} | |
// In-order traversal | |
void inorder(node* n) | |
{ | |
if(n->left != NULL) | |
inorder(n->left); | |
cout << " " << n->key; | |
if (n->right != NULL) | |
inorder(n->right); | |
} | |
// MAIN FUNCTION | |
int main(int argc, char** argv) | |
{ | |
// input | |
string opt; | |
int n; | |
cin >> n; | |
for (int i = 0; i < n; i++) { | |
cin >> opt; | |
if (opt == "insert") { | |
// insert new node | |
int key; | |
cin >> key; | |
insert(key); | |
} | |
if (opt == "print") { | |
inorder(root); | |
cout << endl; | |
preorder(root); | |
cout << endl; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment