Inorder predecessor and successor for a given key in BST


SUBMITTED BY: BadduCoder

DATE: March 5, 2020, 5:11 p.m.

FORMAT: C++

SIZE: 2.5 kB

HITS: 528

  1. // C++ program to find predecessor
  2. // and successor in a BST
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5. // BST Node
  6. struct Node {
  7. int key;
  8. struct Node *left, *right;
  9. };
  10. // Function that finds predecessor and successor of key in BST.
  11. void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)
  12. {
  13. if (root == NULL)
  14. return;
  15. // Search for given key in BST.
  16. while (root != NULL) {
  17. // If root is given key.
  18. if (root->key == key) {
  19. // the minimum value in right subtree
  20. // is predecessor.
  21. if (root->right) {
  22. suc = root->right;
  23. while (suc->left)
  24. suc = suc->left;
  25. }
  26. // the maximum value in left subtree
  27. // is successor.
  28. if (root->left) {
  29. pre = root->left;
  30. while (pre->right)
  31. pre = pre->right;
  32. }
  33. return;
  34. }
  35. // If key is greater than root, then
  36. // key lies in right subtree. Root
  37. // could be predecessor if left
  38. // subtree of key is null.
  39. else if (root->key < key) {
  40. pre = root;
  41. root = root->right;
  42. }
  43. // If key is smaller than root, then
  44. // key lies in left subtree. Root
  45. // could be successor if right
  46. // subtree of key is null.
  47. else {
  48. suc = root;
  49. root = root->left;
  50. }
  51. }
  52. }
  53. // A utility function to create a new BST node
  54. Node* newNode(int item)
  55. {
  56. Node* temp = new Node;
  57. temp->key = item;
  58. temp->left = temp->right = NULL;
  59. return temp;
  60. }
  61. // A utility function to insert
  62. // a new node with given key in BST
  63. Node* insert(Node* node, int key)
  64. {
  65. if (node == NULL)
  66. return newNode(key);
  67. if (key < node->key)
  68. node->left = insert(node->left, key);
  69. else
  70. node->right = insert(node->right, key);
  71. return node;
  72. }
  73. // Driver program to test above function
  74. int main()
  75. {
  76. int key = 65; // Key to be searched in BST
  77. /* Let us create following BST
  78. 50
  79. / \
  80. / \
  81. 30 70
  82. / \ / \
  83. / \ / \
  84. 20 40 60 80
  85. */
  86. Node* root = NULL;
  87. root = insert(root, 50);
  88. insert(root, 30);
  89. insert(root, 20);
  90. insert(root, 40);
  91. insert(root, 70);
  92. insert(root, 60);
  93. insert(root, 80);
  94. Node *pre = NULL, *suc = NULL;
  95. findPreSuc(root, pre, suc, key);
  96. if (pre != NULL)
  97. cout << "Predecessor is " << pre->key << endl;
  98. else
  99. cout << "-1";
  100. if (suc != NULL)
  101. cout << "Successor is " << suc->key;
  102. else
  103. cout << "-1";
  104. return 0;
  105. }

comments powered by Disqus