Delete Node in a BST

update Sep 1, 2017 17:11

LeetCodearrow-up-right

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:

  • Search for a node to remove.

  • 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

Basic Idea:

这里arrow-up-right 有一个关于在BST中删除节点算法的介绍;

我们知道,在BST中删除节点分为三种情况:

  • target node 没有子节点: 此时可以直接删除

  • target node 有一个子节点: 直接用子节点替换target节点

  • target node 有两个子节点:这种情况最为复杂。方法是用其右子树中最小元素(successor)复制后代替target,然后递归删除之前复制过的successor;

具体实现的时候,因为没有parent指针,需要另外写一个函数 remove(targetNode, parentNode),返回替换掉target的新node,用来应付root被移除的情况;

Python Code (新写法,模块化):

Java Code (最初的写法):

update Dec 25, 2017 20:28

Update

还是要建立分模块设计的思想。比如这道题,另外写两个函数 findRightMin(), findNode(),可以令主函数 remove() 更加易读,写的时候也方便。另外注意一点,当待删除节点左右都有孩子的时候,选择用 leftMax 或者 rightMin 替换都可以。

实现的时候,先考虑target node没有孩子的情况,再考虑有两个孩子的情况,再考虑只有一个孩子的情况,这样写逻辑最简单。另外写一个 remove(parent, node) 是为了处理待删除点是 root 的情况。

Python实现见前面。

Java 实现示意:

update 2018-06-10 14:16:39

C++ Solution