Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct node{
- int data, rch, lch;
- node *right, *left;
- };
- class tbt{
- node *root;
- node *dummy;
- public:
- tbt(){
- root=NULL;
- dummy = new node;
- dummy -> left = dummy -> right = NULL;
- dummy -> lch = dummy -> rch = 0;
- }
- void create(int v){
- node* nn = new node;
- nn -> data = v;
- if(root == NULL){
- root = NULL;
- root -> left = root -> right = dummy;
- dummy -> left = root;
- return;
- }
- else{
- node *t, *parent;
- t = root;
- parent = dummy;
- while(t != NULL){
- parent = NULL;
- if(nn -> data < t -> data){
- if(t -> lch == 1){
- t = t -> left;
- }
- else{
- t = NULL;
- }
- }
- else{
- if(t->rch==1){
- t=t->right;
- }
- else{
- t=NULL;
- }
- }
- }
- if(nn -> data < parent -> data)
- {
- nn -> left = parent -> left;
- nn -> right = parent;
- parent -> lch = 1;
- parent -> left = nn;
- }
- else
- {
- nn -> right = parent -> right;
- nn -> left = parent;
- parent -> right = nn;
- parent -> rch = 1;
- }
- return;
- }
- }
- void inorder(){
- node *t;
- t=root;
- while (1)
- {
- while(t->lch==1)
- {
- t=t->left;
- }
- cout<<t->data<<" ";
- while(t->rch==0)
- {
- if(t->right==dummy)
- {
- return;
- }
- else
- {
- t=t->right;
- cout<<t->data<<" ";
- }
- }
- t=t->right;
- }
- }
- void preorder(){
- node *t;
- t=root;
- while(1)
- {
- while(t->lch==1)
- {
- cout<<t->data<<" ";
- t=t->left;
- }
- cout<<t->data<<" ";
- while(t->rch==0)
- {
- if(t->right==dummy)
- {
- return;
- }
- else
- {
- t=t->right;
- }
- }
- t=t->right;
- }
- }
- };
- int main(){
- tbt a;
- a.create(10);
- a.create(20);
- a.create(30);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement