Created
March 15, 2017 00:01
-
-
Save tooshitaka/c416a60515dd713bc92c9206af6ee06b 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); | |
} | |
// Finde key | |
node* find(int key) | |
{ | |
node* n = root; | |
while (n != NULL) { | |
if (n->key == key) | |
return n; | |
if (n->key >= key) | |
n = n->left; | |
else | |
n = n->right; | |
} | |
return NULL; | |
} | |
// 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); | |
} | |
else if (opt == "print") { | |
inorder(root); | |
cout << endl; | |
preorder(root); | |
cout << endl; | |
} | |
else if (opt == "find") { | |
int key; | |
cin >> key; | |
node* result = find(key); | |
if (result != NULL) | |
cout << "yes" << endl; | |
else | |
cout << "no" << endl; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment