题目

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:

  1. root = [5,3,6,2,4,null,7]
  2. key = 3
  3. 5
  4. / \
  5. 3 6
  6. / \ \
  7. 2 4 7
  8. Given key to delete is 3. So we find the node with value 3 and delete it.
  9. One valid answer is [5,4,6,2,null,null,7], shown in the following BST.
  10. 5
  11. / \
  12. 4 6
  13. / \
  14. 2 7
  15. Another valid answer is [5,2,6,null,4,null,7].
  16. 5
  17. / \
  18. 2 6
  19. \ \
  20. 4 7

题意

删除二叉搜索树中的一个结点。

思路

使用递归实现:

  1. 如果 key<root.val,向左递归;
  2. 如果 key>root.val,向右递归;
  3. 如果 key==root.val,分为3中情况:
    1. root没有左子树,那么直接返回root的右子树;
    2. root没有右子树,那么直接返回root的左子树;
    3. root既有左子树又有右子树,那么在root的右子树中找到最小的值,即右子树中最左侧的结点,将它的值赋给root,再删掉这个结点(即上述没有左子树的情况)。也可以找root左子树中最大(最右侧)的结点。

代码实现

Java

  1. class Solution {
  2. public TreeNode deleteNode(TreeNode root, int key) {
  3. if (root == null) {
  4. return null;
  5. }
  6. if (key < root.val) {
  7. root.left = deleteNode(root.left, key);
  8. } else if (key > root.val) {
  9. root.right = deleteNode(root.right, key);
  10. } else if (root.left == null) {
  11. root = root.right;
  12. } else if (root.right == null) {
  13. root = root.left;
  14. } else {
  15. TreeNode cur = root.right;
  16. TreeNode pre = root;
  17. while (cur.left != null) {
  18. cur = cur.left;
  19. pre = pre == root ? root.right : pre.left;
  20. }
  21. root.val = cur.val;
  22. if (pre == root) {
  23. pre.right = cur.right;
  24. } else {
  25. pre.left = cur.right;
  26. }
  27. }
  28. return root;
  29. }
  30. }