193030

Tree create and print

Oct 28th, 2020 (edited)
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include <iostream>
  2.  
  3.  
  4. struct TreeNode
  5. {
  6.     int data;
  7.     struct TreeNode* lchild;
  8.     struct TreeNode* rchild;
  9. } *root = NULL;
  10.  
  11. struct QueueNode
  12. {
  13.     struct TreeNode* data;
  14.     struct QueueNode* next;
  15. } *first = NULL, *rear = NULL;
  16.  
  17. using namespace std;
  18.  
  19. void enqueue(struct TreeNode* x)
  20. {
  21.     if(first == NULL)
  22.     {
  23.         first = new QueueNode;
  24.         first->data = x;
  25.         first->next = NULL;
  26.         rear = first;
  27.     }
  28.     else
  29.     {
  30.         QueueNode *t = new QueueNode;
  31.         t->data = x;
  32.         t->next = NULL;
  33.         rear->next = t;
  34.         rear = t;
  35.     }
  36. }
  37.  
  38.  
  39.  
  40. struct TreeNode* dequeue()
  41. {
  42.     QueueNode *t = first;
  43.     first = first->next;
  44.     struct TreeNode *tempData;
  45.     tempData = t->data;
  46.     delete t;
  47.     return tempData;
  48.  
  49. }
  50.  
  51. int isEmpty()
  52. {
  53.     if(first == NULL)
  54.         return 1;
  55.     else
  56.         return 0;
  57. }
  58.  
  59. void treeCreate()
  60. {
  61.     int x;
  62.     cout << "Enter root value " << endl;
  63.     cin >> x;
  64.     root = new TreeNode;
  65.     root->data = x;
  66.     root->lchild = NULL;
  67.     root->rchild = NULL;
  68.     enqueue(root);
  69.     while(!isEmpty())
  70.     {
  71.         struct TreeNode* p = dequeue();
  72.         cout << "Enter the value of lchild of " << p->data <<  endl;
  73.         cin >> x;
  74.         if(x != -1)
  75.         {
  76.             TreeNode* t;
  77.             t = new TreeNode;
  78.             t->data = x;
  79.             t->lchild = t->rchild = NULL;
  80.             p->lchild = t;
  81.             enqueue(t);
  82.         }
  83.         cout << "Enter the value of rchild of " << p->data <<  endl;
  84.         cin >> x;
  85.         if(x != -1)
  86.         {
  87.             TreeNode* t;
  88.             t = new TreeNode;
  89.             t->data = x;
  90.             t->lchild = t->rchild = NULL;
  91.             p->rchild = t;
  92.             enqueue(t);
  93.         }
  94.  
  95.     }
  96. }
  97.  
  98. void traverseTree(struct TreeNode *p)
  99. {
  100.     if(p)
  101.     {
  102.         traverseTree(p->lchild);
  103.         cout << p->data << " ";
  104.         traverseTree(p->rchild);
  105.     }
  106. }
  107.  
  108.  
  109.  
  110. int main()
  111. {
  112.     treeCreate();
  113.     traverseTree(root);
  114. }
  115.  
Add Comment
Please, Sign In to add comment