[Leetcode]450. Delete Node in a BST

时间:2023-03-09 07:05:28
[Leetcode]450. Delete Node in a BST

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:

  1. Search for a node to remove.
  2. If the node is found, delete the node.

Note: Time complexity should be O(height of tree).

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 思路:分两种情况,一种是要删除的节点只有一个孩子,另一种是要删除的节点有两个孩子;
如果只有一个孩子,那么我们让这个节点引用到他非空的孩子上去,即root = root.right或
root = root.left;如果有两个孩子的话,那么有两种办法,一种是找他右边的最小值,另一种
是找他左边的的最大值。将值赋给该节点,然后删除右边最小值或左边最大值;
 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root==null)
return null;
else if (key<root.val)
root.left = deleteNode(root.left,key);
else if (key>root.val)
root.right = deleteNode(root.right,key);
else {
if (root.left!=null&&root.right!=null){
TreeNode tmp = findMin(root.right);
root.val = tmp.val;
root.right = deleteNode(root.right,root.val);
}
else {
TreeNode tmp = root;
if (root.left==null)
root = root.right;
else if (root.right==null)
root = root.left;
tmp = null;
}
}
return root;
}
private TreeNode findMin(TreeNode root){
if (root==null)
return null;
if (root.left==null)
return root;
return findMin(root.left);
}
}