Advertisement
Guest User

Untitled

a guest
Apr 19th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. BSTnode* remove_node(BSTnode* root, int value) {
  2.     // When root is null
  3.     if (root == NULL) {
  4.         return NULL;
  5.     }
  6.  
  7.     // If value lies in left subtree
  8.     if (value < root->val) {
  9.         root->left = remove_node(root->left, value);
  10.         return root;
  11.     }
  12.     // If value lies in right subtree
  13.     else if (value > root->val) {
  14.         root->right = remove_node(root->right, value);
  15.         return root;
  16.     }
  17.  
  18.     // if value is located in root node
  19.     else {
  20.  
  21.         // node with only one child or no child
  22.         if(root->left == NULL && root->right == NULL) {
  23.             delete root;
  24.             return NULL;
  25.         } else if (root->left == NULL) {
  26.             BSTnode *son = root->right;
  27.             son->parent = root->parent;
  28.             delete root;
  29.             return son;
  30.  
  31.         } else if (root->right == NULL) {
  32.             BSTnode *son = root->left;
  33.             son->parent = root->parent;
  34.             delete root;
  35.             return son;
  36.         }
  37.  
  38.         // node with two children: The inorder successor is the new value
  39.         BSTnode* temp = min(root->right);
  40.  
  41.         // Copy the inorder successor's content to this node
  42.         root->val = temp->val;
  43.  
  44.         // Delete the inorder successor
  45.         root->right = remove_node(root->right, temp->val);
  46.     }
  47.     return root;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement