题目描述
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:
1 | root = [5,3,6,2,4,null,7] |
这题需要在二分查找树中删除节点。
在找到该节点位置之后,二分查找树删除节点的思路为:
- 如果该节点没有子节点,则直接删除
- 如果该节点有左子节点,就找左子树的最大值替换该节点的值,并且删除左子树中的最大节点
- 如果该节点有右子节点,就找右子树的最小值替换该节点的值,并且删除右子树中的最小节点
我使用了循环而非递归来做,所以代码看起来会比较繁琐,但是效率会比递归的更高。
代码实现
1 | # Definition for a binary tree node. |