450. Delete Node in a BST

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

  1. Search for a node to remove.
  2. If the node is found, delete the node.

 

Note: Time complexity should be O(height of tree).

Example:

root = [5,3,6,2,4,null,7]
key = 3

    5
   / \
  3   6
 / \   \
2   4   7

Given key to delete is 3. So we find the node with value 3 and delete it.

One valid answer is [5,4,6,2,null,null,7], shown in the following BST.

    5
   / \
  4   6
 /     \
2       7

Another valid answer is [5,2,6,null,4,null,7].

    5
   / \
  2   6
   \   \
    4 7 

ideas:
1. If the node to be deleted is not in the tree, directly return to the root node
2. There are the following four situations when finding a node
  • This node is a leaf node
  • This node has only left nodes
  • The node has only the right node
  • The node has two nodes, find the smallest node of the right subtree of the node, replace the value of the node with the value of the smallest node, and delete the smallest node
 1 class Solution {
 2 public:
 3     bool find(TreeNode* root, int key){
 4         if(root == NULL) return false;
 5         if(key < root->val) return find(root->left, key);
 6         else if(key > root->val) return find(root->right, key);
 7         else return true;
 8     }
 9     
10     TreeNode* deleteNode(TreeNode* root, int key) {
11         if(!find(root, key)) return root;
12         if(key < root->val) root->left = deleteNode(root->left, key);
13         else if(key > root->val) root->right = deleteNode(root->right, key);
14         else{
15             if(root->left == NULL && root->right == NULL) root = NULL;
16             else if(root->left != NULL && root->right == NULL) root = root->left;
17             else if(root->right != NULL && root->left == NULL) root = root->right;
18             else{
19                     TreeNode *temp = root->right;
20                     while(temp->left != NULL) temp = temp->left;
21                     root->val = temp->val;
22                     root->right = deleteNode(root->right, temp->val);
23             }
24         }
25         return root;
26     }
27 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325083963&siteId=291194637
BST