450. Delete Node in a BST

Posted 巴蜀小小生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

思路:
1.若要删除的结点不在树中,直接返回根结点
2.找到结点有下面四种情况
  • 该节点是叶子结点
  • 该结点只有左结点
  • 该结点只有右结点
  • 该结点有两个结点,找到该结点右子树的最小结点,把该节点的值替换为最小结点的值,删除最小结点
 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 };

 

以上是关于450. Delete Node in a BST的主要内容,如果未能解决你的问题,请参考以下文章

450. Delete Node in a BST

450. Delete Node in a BST

450. Delete Node in a BST

**Leetcode 450. Delete Node in a BST

Leetcode 450. Delete Node in a BST

LC 450. Delete Node in a BST