leetcode450. 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:

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

5
/ \
2   6
\   \
4   7``````

思路和代码

1. 该该节点为叶节点，此时无需进行任何操作，直接删除该节点即可
2. 该节点只有一个子树，则将唯一的直接子节点替换掉当前的节点即可
3. 该节点既有做左子节点又有右子节点。这时候有两种选择，要么选择左子树的最大值，要么选择右子树的最小值填充至当前的节点，再递归的在子树中删除对应的最大值或是最小值。

``````1. 叶节点
5
/ \
2   6
\   \
4   7 （删除4）

5
/ \
2   6
\
7

2. 只有左子树或是只有右子树
5
/ \
3   6
/ \   \
2   4   7（删除6）

5
/ \
3   6
/ \
2   4

3. 既有左子树又有右子树
6
/ \
3   7
/ \   \
2   5   8 （删除6）
/
4

5
/ \
3   7
/ \   \
2   5   8 （删除5）
/
4

5
/ \
3   7
/ \   \
2   4   8 （删除5）``````

``````    public TreeNode deleteNode(TreeNode cur, int key) {
if(cur == null) return null;
else if(cur.val == key) {
if(cur.left != null && cur.right != null) {
TreeNode left = cur.left;
while(left.right != null) {
left = left.right;
}
cur.val = left.val;
cur.left = deleteNode(cur.left, left.val);
}else if(cur.left != null) {
return cur.left;
}else if(cur.right != null){
return cur.right;
}else {
return null;
}
}else if(cur.val > key) {
cur.left = deleteNode(cur.left, key);
}else {
cur.right = deleteNode(cur.right, key);
}
return cur;
}``````

2.7k 声望2k 粉丝

0 条评论