You are currently viewing Easy Binary Search Tree Code

Easy Binary Search Tree Code

Binary Search Tree Creation Code

This code is for Binary search tree creation. As we know in Binary Search Tree left sub tree will contain lesser value than the parent and right sub tree will contain greater value than the parent. So in this code nodes are inserted on the basis of there position. After searching the proper position of the new node by traversing left or right, is attached with the previous node. Execute In-order traversal for checking whether the Binary Search Tree is created properly or not because it will display all the elements in ascending order.

For Such more codes click here and for video tutorial click here.

				
					#include<stdio.h>

#include<stdlib.h>


typedef struct BinarySearchTree {
  struct BinarySearchTree * left;
  struct BinarySearchTree * right;
  int val;
}
bst;

bst * create(bst * , int);
void inorder(bst * );
void preorder(bst * );
void postorder(bst * );

int main() {
  bst * root = NULL;
  int g, ch;
  while (1) {
    printf("\n 1) Insert Node\n 2) Preorder traversal\n 3) Inorder traversal\n 4) Postorder traversal\n 6) Exit");
    printf("\n Enter your choice : ");
    scanf("%d", & ch);
    switch (ch) {
    case 1:
      printf("\nInsert value for the tree: ");
      scanf("%d", & g);
      root = create(root, g);
      break;
    case 2:
      printf("\nValues in Preorder Traversal : ");
      preorder(root);
      break;
    case 3:
      printf("\nValues in Inorder Traversal : ");
      inorder(root);
      break;
    case 4:
      printf("\nValues in Postorder Traversal : ");
      postorder(root);
      break;
    case 6:
      exit(0);
    }
  }
}

bst * create(bst * root, int p) {
  bst * temp, * pre, * ptr;
  temp = (bst * ) malloc(sizeof(bst));
  temp -> val = p;
  temp -> right = temp -> left = NULL;
  if (root == NULL) {
    root = temp;
  } else {
    ptr = root;
    while (ptr != NULL) {
      pre = ptr;
      if (ptr -> val > p)
        ptr = ptr -> left;
      else
        ptr = ptr -> right;
    }
    if (pre -> val > p)
      pre -> left = temp;
    else
      pre -> right = temp;
  }
  return root;
}

void preorder(bst * root) {
  if (root != NULL) {
    printf("%d,", root -> val);
    preorder(root -> left);
    preorder(root -> right);
  }
}

void inorder(bst * root) {
  if (root != NULL) {
    inorder(root -> left);
    printf("%d,", root -> val);
    inorder(root -> right);
  }
}

void postorder(bst * root) {
  if (root != NULL) {
    postorder(root -> left);
    postorder(root -> right);
    printf("%d,", root -> val);
  }
}
				
			

Leave a Reply