Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct Data {
- int id;
- char name[];
- }Data;
- typedef struct Node{
- Data data;
- struct Node *left, *right;
- }Node;
- typedef Node Tree;
- Node * newNode(int val){
- Node* node = malloc(sizeof(Node));
- node->data.id = val;
- node->left = node->right = NULL;
- return node;
- }
- Node * addRight(Node *root,int val){
- if(root) {
- Node* new = newNode(val);
- root->right = new;
- return new;
- }
- return NULL;
- }
- Node * addLeft(Node *root,int val){
- if(root) {
- Node* new = newNode(val);
- root->left = new;
- return new;
- }
- return NULL;
- }
- void kill(Node * node){ free(node); }
- // START OF TRAVERSING FUNCTIONS.
- void preTravers(Tree *root){
- if(root) {
- printf("[%d]\n", root->data.id);
- preTravers(root->left);
- preTravers(root->right);
- }
- }
- void postTravers(Tree *root){
- if(root) {
- postTravers(root->left);
- postTravers(root->right);
- printf("[%d]\n", root->data.id);
- }
- }
- void inTravers(Tree *root){
- if(root) {
- inTravers(root->left);
- printf("[%d]\n", root->data.id);
- inTravers(root->right);
- }
- }
- // END OF TRAVERSING FUNCTIONS.
- // START SHOWING FUNCTIONS.
- void inShow(Tree *root,int currentDepth){
- if(root) {
- inShow(root->right,currentDepth+1);
- int i; for(i=0;i<currentDepth;i++) printf("\t");
- printf("%3d ", root->data.id);
- inShow(root->left,currentDepth+1);
- }else
- printf("\n");
- }
- // END SHOWING FUNCTIONS.
- // START OF INSERTING IN BST FUNCTIONS.
- void insert(Tree *root,int val){
- Node * node = newNode(val);
- if(root) {
- if(val < root->data.id ){
- // GO LEFT
- // if there is no left node
- if(!root->left)
- root->left = node;
- else // there is a node insert to it
- insert(root->left,val);
- }else{
- // GO RIGHT
- // if there is no right node
- if(!root->right)
- root->right = node;
- else
- insert(root->right,val);
- }
- }
- // return node;
- }
- // END OF INSERTING IN BST FUNCTIONS.
- int main(){
- system("clear");
- Tree *root = newNode(80);
- /*Tree *node1 = addLeft(root,2);
- Tree *node2 = addRight(root,10);
- addLeft(node1,1);
- addRight(addRight(node1,4),5);
- addLeft(node2,9);
- addRight(addLeft(addRight(node2,100),50),60);*/
- // preTravers(root);
- // postTravers(root);
- // inTravers(root);
- insert(root,100);
- insert(root,70);
- insert(root,50);
- insert(root,200);
- insert(root,150);
- insert(root,60);
- insert(root,90);
- insert(root,95);
- inShow(root,0);
- /*kill(node2);
- kill(node1);*/
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment