Guest User

Untitled

a guest
May 19th, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include<iostream>
  2. #include<malloc.h>
  3. using namespace std;
  4. typedef struct tree
  5. {
  6.     int number;
  7.     struct tree *leftChild;
  8.     struct tree *rightChild;
  9.  
  10. } node;
  11. node *root=NULL;
  12. void inorder(node *root){
  13.     if(root==NULL) return;
  14.     inorder(root->leftChild);
  15.     inorder(root->rightChild);
  16. }
  17. void insertNode(int value)
  18. {
  19.     node *tempNode;
  20.     node *currentNode=NULL;
  21.     node *parentNode=NULL;
  22.  
  23.     tempNode = (node *) malloc(sizeof(node));
  24.     tempNode->number = value;
  25.  
  26.     //For the very first call
  27.     if(root==NULL)
  28.     {
  29.         root = tempNode;
  30.     }
  31.     else
  32.     {
  33.         currentNode = root;
  34.         parentNode = NULL;
  35.  
  36.         while(1)
  37.         {
  38.             parentNode = currentNode;
  39.  
  40.             if(value <= parentNode->number)
  41.             {
  42.                 currentNode = currentNode->leftChild;
  43.  
  44.                 if(currentNode==NULL)
  45.                 {
  46.                     parentNode->leftChild = tempNode;
  47.                     return;
  48.                 }
  49.             }
  50.             else
  51.             {
  52.                 currentNode = currentNode->rightChild;
  53.  
  54.                 if(currentNode==NULL)
  55.                 {
  56.                     parentNode->rightChild = tempNode;
  57.                     return;
  58.                 }
  59.             }
  60.  
  61.         }
  62.     }
  63. }
  64. int main()
  65. {
  66.     int total_node;
  67.     cout<<"Enter total node amount:\n";
  68.     cin>>total_node;
  69.     for(int i=1; i<=total_node; i++) insertNode(i);
  70.     cout<<endl;
  71.     inorder(root);
  72. }
Add Comment
Please, Sign In to add comment