Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- struct BST{
- int data;
- BST * left;
- BST * right;
- };
- #include "bst_helper.cpp"
- BST * insert_Node(BST * root, int value)
- {
- if(root == NULL)
- {
- BST * temp = (BST*) malloc(sizeof(BST));
- temp->data = value;
- temp->left = NULL;
- temp->right = NULL;
- return temp;
- }
- if (value <= root->data)
- root->left = insert_Node(root->left, value);
- else if (value > root->data)
- root->right = insert_Node(root->right, value);
- return root;
- }
- BST * minimum_Node(BST * root)
- {
- while(root->left != NULL)
- root = root->left;
- return root;
- }
- BST * delete_Node(BST * root, int key)
- {
- if(root == NULL)
- return root;
- else if(key < root->data)
- root->left = delete_Node(root->left, key);
- else if(key > root->data)
- root->right = delete_Node(root->right, key);
- else
- {
- BST * temp = (BST*) malloc(sizeof(BST));
- // no child
- if((root->left == NULL) && (root->right == NULL))
- {
- free(root);
- root = NULL;
- }
- // 1 child (right)
- else if(root->left == NULL)
- {
- temp = root;
- root = root->right;
- free(temp);
- }
- // 1 child (left)
- else if(root->right == NULL)
- {
- temp = root;
- root = root->left;
- free(temp);
- }
- // 2 children
- else
- {
- temp = minimum_Node(root->right);
- root->data = temp->data;
- root->right = delete_Node(root->right, temp->data);
- }
- }
- return root;
- }
- void inorder(BST * root)
- {
- if(root == NULL)
- return;
- inorder(root->left);
- printf("%d ", root->data);
- inorder(root->right);
- }
- void level_order(BST * root)
- {
- if(root == NULL)
- return;
- Queue * q = (Queue*)(malloc(sizeof(Queue)));
- q = NULL;
- q = enqueue(q, root);
- BST * cur = (BST*) malloc(sizeof(BST));
- while(!isEmpty(q))
- {
- cur = top(q);
- q = dequeue(q);
- printf("%d ", cur->data);
- if(cur->left != NULL)
- q = enqueue(q, cur->left);
- if(cur->right != NULL)
- q = enqueue(q, cur->right);
- }
- }
- bool search_key(BST * root, int key)
- {
- //ITERATIVE
- while(root!=NULL)
- {
- if(root->data == key)
- return true;
- if(key > root->data)
- root = root->right;
- else if(key < root->data)
- root = root->left;
- }
- return false;
- }
- int main()
- {
- BST * root = (BST*) malloc(sizeof(BST));
- root = NULL;
- root = insert_Node(root, 90);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement