450. Delete Node in a BST
450. Delete Node in a BST
1 | 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 |
Example 1:1
2
3
4
5Input: root = [5,3,6,2,4,null,7], key = 3
Output: [5,4,6,2,null,null,7]
Explanation: 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 above BST.
Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.
Example 2:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19Input: root = [5,3,6,2,4,null,7], key = 0
Output: [5,3,6,2,4,null,7]
Explanation: The tree does not contain a node with value = 0.
Example 3:
Input: root = [], key = 0
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 104].
-105 <= Node.val <= 105
Each node has a unique value.
root is a valid binary search tree.
-105 <= key <= 105
Follow up: Could you solve it with time complexity O(height of tree)?
难度 : 中等
思路
首先要找到要删除的节点,然后执行删除。因为是BST所以可以根据要删除节点的值和当前节点的值的大小
来决定查找的子树。
查找要删除节点分3种情况
- 要删除的节点比当前节点的值大,递归查找右节点
- 要删除的节点比当前节点的值小,递归查找左节点
- 要删除的节点和当前节点的值相等 执行删除当前的节点。这里分为下面几种情况
- 当前节点为叶子节点 直接删除
- 当前节点的右节点为空,返回左节点
- 当前节点的左节点为空返回右节点
- 当前节点的左右节点都不为空,找到当前节点左子树的最左边的节点把值互换然后递归调用删除方法
时间复杂度: O(h) h 为BST的树的高度
1 | /** |