Write a binary search tree demo program to insert a new node and display the sorted list.

Source Code

/* bst.cpp : Binary search tree demo program to insert a new node and display the sorted list. */
#include "stdafx.h"
#include<stdlib.h>
struct node{
  int value;
  struct node   *left;
  struct node   *right;

};
struct node * new_node(int val)
{
    struct node * new_node = (struct node *)malloc(sizeof(struct node));
    if(new_node)
    {
       new_node->value = val;
       new_node->left = 0;
       new_node->right = 0;
    }
    else
    {
      exit(-1);
    }
    return new_node;
}
struct node * insert(struct node * root, int value)
{
  if(root ==  NULL)
  {
    return new_node(value);
  }
  else
  {
    if(value == root->value)
    {
      printf("Value already there!");
      return NULL;
    }
    if(value < root->value)
    {
      root->left = insert(root->left, value);
    }
    else
    {
      root->right = insert(root->right, value);
    }
    return root;
  }
}
void printout(node * tree) {
   if(tree->left) printout(tree->left);
   printf("%d\n",tree->value);
   if(tree->right) printout(tree->right);
}

int main(int argc, char* argv[])
{
  struct node * head = NULL;
  int array[] = { 9,6,3,5,2,1,9,0,4, 50, 30,};
  for(int i = 0; i < sizeof(array)/sizeof(int); i++)
  {
    if(head == NULL)
    head = insert(head, array[i]);
    else
      insert(head, array[i]);
  }
  printout(head);
 return 0;
}

Find More from our code collection
Armstrong number, binary number to a decimal number, bubble sort, decimal number to binary number, factorial of the given number factors, fibonacci numbers, HCF and LCM, matrix, mergesort, salary of the employee. palindrome, quadratic equation, star patterns, series etc. and much more...
#Return to Example Source Code