Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- BSTnode* remove_node(BSTnode* root, int value) {
- // When root is null
- if (root == NULL) {
- return NULL;
- }
- // If value lies in left subtree
- if (value < root->val) {
- root->left = remove_node(root->left, value);
- return root;
- }
- // If value lies in right subtree
- else if (value > root->val) {
- root->right = remove_node(root->right, value);
- return root;
- }
- // if value is located in root node
- else {
- // node with only one child or no child
- if(root->left == NULL && root->right == NULL) {
- delete root;
- return NULL;
- } else if (root->left == NULL) {
- BSTnode *son = root->right;
- son->parent = root->parent;
- delete root;
- return son;
- } else if (root->right == NULL) {
- BSTnode *son = root->left;
- son->parent = root->parent;
- delete root;
- return son;
- }
- // node with two children: The inorder successor is the new value
- BSTnode* temp = min(root->right);
- // Copy the inorder successor's content to this node
- root->val = temp->val;
- // Delete the inorder successor
- root->right = remove_node(root->right, temp->val);
- }
- return root;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement