Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. struct node
  4. {
  5. int key;
  6. struct node *left, *right;
  7. };
  8.  
  9. // A utility function to create a new BST node
  10. struct node *newNode(int item)
  11. {
  12. struct node *temp = (struct node *)malloc(sizeof(struct node));
  13. temp->key = item;
  14. temp->left = temp->right = NULL;
  15. return temp;
  16. }
  17.  
  18. // A utility function to do inorder traversal of BST
  19. void inorder(struct node *root)
  20. {
  21. if (root != NULL)
  22. {
  23. inorder(root->left);
  24. printf("%d \n", root->key);
  25. inorder(root->right);
  26. }
  27. }
  28.  
  29. /* A utility function to insert a new node with given key in BST */
  30. struct node* insert(struct node* node, int key)
  31. {
  32. /* If the tree is empty, return a new node */
  33. if (node == NULL) return newNode(key);
  34.  
  35. /* Otherwise, recur down the tree */
  36. if (key < node->key)
  37. node->left = insert(node->left, key);
  38. else if (key > node->key)
  39. node->right = insert(node->right, key);
  40.  
  41. /* return the (unchanged) node pointer */
  42. return node;
  43. }
  44.  
  45. // Driver Program to test above functions
  46. int main()
  47. {
  48. /* Let us create following BST
  49. 50
  50. / \
  51. 30 70
  52. / \ / \
  53. 20 40 60 80 */
  54. struct node *root = NULL;
  55. root = insert(root, 50);
  56. insert(root, 30);
  57. insert(root, 20);
  58. insert(root, 40);
  59. insert(root, 70);
  60. insert(root, 60);
  61. insert(root, 80);
  62.  
  63. // print inoder traversal of the BST
  64. inorder(root);
  65.  
  66. return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement