我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/delete-node-in-a-bst/description/
题目描述:
知识点:二分搜索树
思路:二分搜索树删除节点的经典操作
本题考查的完全是数据结构的知识,二分搜索树的删除节点操作是二分搜索树中最难的一个操作,为了完成这一操作,我们需要定义几个函数。
(1)containNode()函数。该函数传入一个TreeNode型变量treeNode和一个int型变量key,返回一个boolean类型结果。该函数用来判断在以treeNode为根节点的二分搜索树中是否有值为key的节点。该函数是递归实现的
(2)findMin()函数。该函数传入一个TreeNode型变量treeNode,返回一个TreeNode型结果。该函数用来寻找在以treeNode为根节点的二分搜索树中值最小的节点。
(3)delMin()函数。该函数传入一个TreeNode型变量treeNode,返回一个TreeNode型结果。该函数用来删除在以treeNode为根结点的二分搜索树中值最小的节点,并返回删除最小节点后新的二分搜索树的根节点。该函数是递归实现的。
接下来我们实现删除节点的操作。
(1)首先,我们调用containNode()函数判断在root节点为根结点的二分搜索树中是否存在值为key的节点,如果不存在,直接返回root。
(2)如果root的值和key值相等,那么root节点就是要删除的节点。
a.如果root节点的左节点为null,我们直接返回root节点的右节点即可。
b.如果root节点的右节点为null,我们直接返回root节点的左节点即可。
c.如果root节点的左右节点均不为null,这种情况比较复杂,分为以下几步:
c-1:调用findMin()函数,寻找到以root的右节点为根节点的二分搜索树中的最小的节点,记作successor。
c-2:调用delMin()函数,删除以root的右节点为根结点的二分搜索树中的最小的节点,并令其结果作为successor的右节点。
c-3:令successor的左节点为root的左节点,并返回successor节点。
(3)如果root的值比key值小,说明所寻找的节点在root节点的右子树中,我们递归调用删除节点的函数在以root的右节点为根结点的二分搜索树中删除值为key的节点,并令其返回结果为root的右孩子,返回root节点。
(4)如果root的值比key值大,说明所寻找的节点在root节点的左子树中,我们递归调用删除节点的函数在以root的左节点为根结点的二分搜索树中删除值为key的节点,并令其返回结果为root的左孩子,返回root节点。
整个过程的时间复杂度如题目要求的那样,是O(h),其中h为二分搜索树的高度。而对于空间复杂度,也是O(h)级别的。
JAVA代码:
public class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(!containNode(root, key)) {
return root;
}
if(root.val == key) {
if(root.left == null) {
return root.right;
}else if(root.right == null) {
return root.left;
}
TreeNode successor = findMin(root.right);
successor.right = delMin(root.right);
successor.left = root.left;
return successor;
}else if(root.val < key) {
root.right = deleteNode(root.right, key);
return root;
}else {
root.left = deleteNode(root.left, key);
return root;
}
}
private boolean containNode(TreeNode treeNode, int key) {
if(treeNode == null) {
return false;
}
if(treeNode.val == key) {
return true;
}else if(treeNode.val > key) {
return containNode(treeNode.left, key);
}else {
return containNode(treeNode.right, key);
}
}
/*
* return a treeNode whose key is the minimum in the tree
*/
private TreeNode findMin(TreeNode treeNode) {
TreeNode cur = treeNode;
while(cur != null) {
if(cur.left == null) {
return cur;
}
cur = cur.left;
}
return cur;
}
/*
* return a treeNode after deleting its treeNode whose key is the minimum
*/
private TreeNode delMin(TreeNode treeNode) {
if(treeNode.left == null) {
return treeNode.right;
}
treeNode.left = delMin(treeNode.left);
return treeNode;
}
}
LeetCode解题报告: