问题:node
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.ide
Basically, the deletion can be divided into two stages:函数
Note: Time complexity should be O(height of tree).测试
Example:spa
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 Another valid answer is [5,2,6,null,4,null,7]. 5 / \ 2 6 \ \ 4 7
解决:递归
【题意】rem
本题让咱们删除二叉搜索树中的一个节点,难点在于删除完节点并补上那个节点的位置后还应该是一棵二叉搜索树。被删除掉的节点位置,不必定是由其的左右子节点补上,好比下面这棵树:it
7
/ \
4 8
/ \
2 6
\ /
3 5io若是咱们要删除节点4,那么应该将节点5补到4的位置,这样才能保证仍是BST,那么结果是以下这棵树:class
7
/ \
5 8
/ \
2 6
\
3
① 递归方法解决:首先判断根节点是否为空。因为BST的左<根<右的性质,使得咱们能够快速定位到要删除的节点,咱们对于当前节点值不等于key的状况,根据大小关系对其左右子节点分别调用递归函数。若当前节点就是要删除的节点,咱们首先判断是否有一个子节点不存在,那么咱们就将root指向另外一个节点,若是左右子节点都不存在,那么root就赋值为空了,也正确。难点就在于处理左右子节点都存在的状况,咱们须要在右子树找到最小值,即右子树中最左下方的节点,而后将该最小值赋值给root,而后再在右子树中调用递归函数来删除这个值最小的节点。
class Solution { //8ms
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (root.val > key){
root.left = deleteNode(root.left,key);
}else if (root.val < key){
root.right = deleteNode(root.right,key);
}else {
if (root.left == null || root.right == null){
root = (root.left != null) ? root.left : root.right;
}else {
TreeNode cur = root.right;
while(cur.left != null){
cur = cur.left;
}
root.val = cur.val;
root.right = deleteNode(root.right,cur.val);
}
}
return root;
}
}
【注】有一个有问题的地方,上面的例子中,删除3时,结果错误。。。多是测试的问题?
② 非递归方法解决。
class Solution { //8ms public TreeNode deleteNode(TreeNode root, int key) { TreeNode cur = root;//指向要删除的节点 TreeNode pre = null;//指向要删除节点的父节点 while(cur != null){ if (cur.val == key) break; pre = cur; if (cur.val > key){ cur = cur.left; }else { cur = cur.right; } } if (cur == null) return root; if (pre == null) return deleteNode(cur); if (pre.left != null && pre.left.val == key){ pre.left = deleteNode(cur); }else { pre.right = deleteNode(cur); } return root; } public TreeNode deleteNode(TreeNode node){ if (node.left == null && node.right == null) return null; if (node.left == null || node.right == null){ return node.left == null ? node.right : node.left; } TreeNode pre = node; TreeNode cur = node.right; while (cur.left != null){ pre = cur; cur = cur.left; } node.val = cur.val; if (pre == node){ node.right = cur.right; }else { pre.left = cur.right; } return node; } }