Last active
August 21, 2017 03:41
-
-
Save malintha/0ca5643aa86b2574765ad9ff35de912e 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 <stdio.h> | |
using namespace std; | |
struct node { | |
int key; | |
node *parent; | |
node *left; | |
node *right; | |
}; | |
class btree { | |
public: | |
btree(); | |
void insert(int, node*); | |
void inordertraverse(node*); | |
private: | |
node *root; | |
}; | |
btree::btree(){} | |
void btree::insert(int key, node *x) { | |
printf("Insert %d\n",key); | |
node *z = new node(); | |
z->key = key; | |
node *y = new node(); | |
while(x!=NULL) { | |
y = x; | |
if(z->key < x->key) { | |
x = x->left; | |
} | |
else { | |
x = x->right; | |
} | |
} | |
z->parent = y; | |
if(!y) { | |
this->root = z; | |
} | |
else if(z->key < y->key) { | |
y->left = z; | |
} | |
else { | |
y->right = z; | |
} | |
} | |
void btree::inordertraverse(node* tree) { | |
if(tree) { | |
inordertraverse(tree->left); | |
cout<<tree->key<<" "<<endl; | |
inordertraverse(tree->right); | |
} | |
} | |
int main() { | |
btree bst; | |
node root = node(); | |
root.key=3; | |
bst.insert(2, &root); | |
bst.insert(4, &root); | |
bst.insert(1, &root); | |
bst.insert(6, &root); | |
bst.insert(7, &root); | |
bst.inordertraverse(&root); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment