Advertisement
AquaBlitz11

Binary Search Tree - Insertion/Preorder/Inorder/Postorder

Mar 7th, 2018
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct Node {
  6.     int key;
  7.     Node *left, *right;
  8. };
  9.  
  10. // this function creates new node with number x and return the pointer to it
  11. Node *createNode(int x)
  12. {
  13.     Node *newNode = new Node();
  14.     newNode->key = x;
  15.     newNode->left = NULL;
  16.     newNode->right = NULL;
  17.     return newNode;
  18. }
  19.  
  20. // this function inserts node 'x' a tree rooted at 'root'
  21. // it will return root of the tree after update
  22. // so you must use it like this:
  23. // vvvvvvvvvvvvvvvvv
  24. // root = insert(root, x); -------- (*)
  25. // ^^^^^^^^^^^^^^^^^
  26. Node *insert(Node *root, int x)
  27. {
  28.     if (root == NULL) // if empty, build a new node and return
  29.         return createNode(x);
  30.     // if exists, go left or go right
  31.     if (x < root->key) {
  32.         root->left = insert(root->left, x);
  33.         // ^ this matches (*) pattern
  34.     } else {
  35.         root->right = insert(root->right, x);
  36.         // ^ this matches (*) pattern
  37.     }
  38.     // don't forget to return original root after finishing
  39.     return root;
  40. }
  41.  
  42. void preorder(Node *root)
  43. {
  44.     if (root == NULL) return;
  45.     printf("%d ", root->key);
  46.     preorder(root->left);
  47.     preorder(root->right);
  48. }
  49.  
  50. void postorder(Node *root)
  51. {
  52.     if (root == NULL) return;
  53.     postorder(root->left);
  54.     postorder(root->right);
  55.     printf("%d ", root->key);
  56. }
  57.  
  58. void inorder(Node *root)
  59. {
  60.     if (root == NULL) return;
  61.     inorder(root->left);
  62.     printf("%d ", root->key);
  63.     inorder(root->right);
  64. }
  65.  
  66. int main()
  67. {
  68.     Node *root = NULL;
  69.     root = insert(root, 5);
  70.     root = insert(root, 10);
  71.     root = insert(root, 3);
  72.     root = insert(root, 7);
  73.     preorder(root);
  74.     printf("\n");
  75.     postorder(root);
  76.     printf("\n");
  77.     inorder(root);
  78.     printf("\n");
  79.  
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement