LoganBlackisle

BST_delete

Jun 16th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. package prep_33_binarysearchtrees;
  2.  
  3. public class BST_delete {
  4. /* Class containing left and right child of current node and key value */
  5. public class Node {
  6. int key;
  7. Node left, right;
  8.  
  9. public Node(int item) {
  10. key = item;
  11. left = right = null;
  12. }
  13. }
  14.  
  15. // Root of BST
  16. public Node root;
  17.  
  18. // Constructor
  19. public BST_delete() {
  20. root = null;
  21. }
  22.  
  23. // This method mainly calls deleteRec()
  24. public void deleteKey(int key) {
  25. root = deleteRec(root, key);
  26. }
  27.  
  28. /* A recursive function to insert a new key in BST */
  29. public Node deleteRec(Node root, int key) {
  30. if (root == null) // Base Case: If the tree is empty
  31. return root;
  32. if (key < root.key) // Otherwise, recur down the tree
  33. root.left = deleteRec(root.left, key);
  34. else if (key > root.key)
  35. root.right = deleteRec(root.right, key);
  36.  
  37. // if key is same as root's key, then This is the node
  38. // to be deleted
  39. else {
  40. // node with only one child or no child
  41. if (root.left == null)
  42. return root.right;
  43. else if (root.right == null)
  44. return root.left;
  45.  
  46. // node with two children: Get the inorder successor (smallest
  47. // in the right subtree)
  48. root.key = minValue(root.right);
  49.  
  50. // Delete the inorder successor
  51. root.right = deleteRec(root.right, root.key);
  52. }
  53.  
  54. return root;
  55. }
  56.  
  57. public int minValue(Node root) {
  58. int minv = root.key;
  59. while (root.left != null) {
  60. minv = root.left.key;
  61. root = root.left;
  62. }
  63. return minv;
  64. }
  65.  
  66. // This method mainly calls insertRec()
  67. public void insert(int key) {
  68. root = insertRec(root, key);
  69. }
  70.  
  71. /* A recursive function to insert a new key in BST */
  72. public Node insertRec(Node root, int key) {
  73. if (root == null) { // If the tree is empty, return a new node
  74. root = new Node(key);
  75. return root;
  76. }
  77. if (key < root.key) // Otherwise, recur down the tree
  78. root.left = insertRec(root.left, key);
  79. else if (key > root.key)
  80. root.right = insertRec(root.right, key);
  81. return root; // return the (unchanged) node pointer
  82. }
  83.  
  84. // This method mainly calls InorderRec()
  85. public void inorder() {
  86. inorderRec(root);
  87. }
  88.  
  89. // A utility function to do inorder traversal of BST
  90. public void inorderRec(Node root) {
  91. if (root != null) {
  92. inorderRec(root.left);
  93. System.out.print(root.key + " ");
  94. inorderRec(root.right);
  95. }
  96. }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment