0
点赞
收藏
分享

微信扫一扫

[LeetCode]Delete Node in a BST


Question
Delete a node in a BST.

Basically, the deletion can be divided into two stages:

Search for a node to remove.
If the node is found, delete the node.
Example:

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

本题难度Medium。

递归

【复杂度】
时间 O(logN) 空间 O(1)

【思路】
利用递归法查找key,找到该node后需要讨论:

  1. node没有儿子。返回null
  2. node有1个儿子。返回儿子
  3. node有2个儿子。这个比较麻烦。我们利用node的右子树的最小值替换node的值,然后到node的右子树去删除该最小值即可。

【代码】

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
//require
if(root==null)
return root;
//invariant
if(key<root.val)
root.left=deleteNode(root.left,key);
else if(root.val<key)
root.right=deleteNode(root.right,key);
else{
//two children
if(root.left!=null&&root.right!=null){
TreeNode tmp=findMin(root.right);
root.val=tmp.val;
root.right=deleteNode(root.right,root.val);
}else{
//one child or zero
if(root.left==null)
root=root.right;
else
root=root.left;
}
}
//ensure
return root;
}
private TreeNode findMin(TreeNode root){
while(root.left!=null)
root=root.left;
return root;
}
}

参考
《数据结构与算法分析:C语言描述》 第2版 4.3.5节


举报

相关推荐

0 条评论