Skip to content

Instantly share code, notes, and snippets.

@malintha
Last active August 21, 2017 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malintha/0ca5643aa86b2574765ad9ff35de912e to your computer and use it in GitHub Desktop.
Save malintha/0ca5643aa86b2574765ad9ff35de912e to your computer and use it in GitHub Desktop.
#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