。。。。
一、删除节点
删除二叉搜索树节点无非就三种情况:删除叶子节点、删除度为1的节点、删除度为2的节点。
1.1. 删除叶子节点
叶子节点直接删除即可,例如图例中的节点3、5、8、10
。
删除节点是左子节点:
1 | node == node.parent.left |
删除节点是右子节点:
1 | node == node.parent.right |
删除节点是根节点:
1 | node.parent = null |
1.2. 删除度为1的节点
用子节点替代原节点的位置,即可实现删除度为1的节点。例如删除上图中的节点4、9
。
假设child
是node.left
或者child
是node.right
,用child
替代node
的位置:
如果node
是左子节点:
1 | child.parent = node.parent |
如果node
是右子节点:
1 | child.parent = node.parent |
如果node
是根节点:
1 | root = child |
1.3. 删除度为2的节点
删除度为2的节点,需要保证二叉搜索树的性质:左子树节点值小于右子树节点值。因此先用前驱或者后继节点的值覆盖原节点的值,然后删除相应的前驱或者后继节点,这样就能够满足所需。
如果一个节点的度为2,那么它的前驱、后继节点的度只可能是1和0。
例:删除节点5,找到节点5的前驱或后继并替换。
1.4. 完整代码
1 | // 删除值对应的节点 |
二、LeetCode
删除二叉搜索树中的节点:https://leetcode-cn.com/problems/delete-node-in-a-bst/
二叉搜索树中的搜索:https://leetcode-cn.com/problems/search-in-a-binary-search-tree/
二叉搜索树中的插入操作:https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/
验证二叉搜索树:https://leetcode-cn.com/problems/validate-binary-search-tree/comments/
二叉搜索树的最小绝对差:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/comments/
二叉搜索树结点最小距离:https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/comments/
将有序数组转换为二叉搜索树:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/
二叉搜索树的范围和:https://leetcode-cn.com/problems/range-sum-of-bst/
二叉搜索树的最近公共祖先:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
二叉搜索树中第K小的元素:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
二叉搜索树迭代器:https://leetcode-cn.com/problems/binary-search-tree-iterator/
恢复二叉搜索树:https://leetcode-cn.com/problems/recover-binary-search-tree/