Tree - 450. Delete Node in a BST

80

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

思路:

题目意思就是让在一个bst中删除一个节点,删除的时候分类讨论就可以,有三种情况,一种是被删除节点只有左子树为空,一种是只有右子树为空,一种是两颗子树都不为空,前两种好处理,直接把不为空的那个子节点替换掉父节点位置就可以,但是如果是左右孩子又不为空,那就需要注意,可以选择左子树的最大值或者右子树的最小值来放在当前位置,这里为了方便,就选择右子树的最小值,也就是被删除节点的后继节点来放到被删除节点的位置。

代码:

go:

/**

 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func deleteNode(node *TreeNode, key int) *TreeNode {
    if node == nil {
        return nil
    }

    if key < node.Val {
        node.Left = deleteNode(node.Left, key)
        return node
    } else if key > node.Val {
        node.Right = deleteNode(node.Right, key)
        return node
    } else { // key == node.Val
        // 1. 左子树为空
        if node.Left == nil {
            rightNode := node.Right
            node.Right = nil
            return rightNode
        }

        // 2. 右子树为空
        if node.Right == nil {
            leftNode := node.Left
            node.Left = nil
            return leftNode
        }

        // 3. 左右子树都不为空
        // 找到待删除的节点的后继(比待删除节点的最小节点),然后用这个后继代替待删除的节点. Hibbard deletion
        successor := minimum(node.Right)
        successor.Right = removeMinNode(node.Right)
        successor.Left = node.Left
        return successor
    }
}

// 以root为根的bst的最小值
func minimum(root *TreeNode) *TreeNode {
	if root.Left == nil {
		return root
	}
	return minimum(root.Left)
}

// 删除以root为根的bst的最小值,并返回这个位置应该变成的节点
func removeMinNode(node *TreeNode) *TreeNode {
	if node.Left == nil {
		rightNode := node.Right
		node.Right = nil
		return rightNode
	}

	node.Left = removeMinNode(node.Left)
	return node
}