题目链接:https://leetcode.cn/problems/delete-node-in-a-bst/
方法一 迭代
1 方法思想
2 代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
// 迭代:两个父节点
if (root == null) return root;
TreeNode curParent = null;
TreeNode cur = root;
while (cur != null && cur.val != key) {
curParent = cur;
if (cur.val > key) {
cur = cur.left;
}else {
cur = cur.right;
}
}
if (cur == null) {
return root;
} else {
if (cur.right == null && cur.left == null) {
cur = null;
//return root;
}else if (cur.left == null) {
cur = cur.right;
// return root;
}else if (cur.right == null) {
cur = cur.left;
// return root;
}else {
TreeNode minRight = cur.right;
TreeNode minRightParent = cur;
while (minRight.left != null) {
minRightParent = minRight;
minRight = minRight.left;
}
if (minRightParent.val == cur.val){
cur.right = minRight.right;
}else {
minRightParent.left = minRight.right;
}
minRight.left = cur.left;
minRight.right = cur.right;
cur = minRight;
}
}
if (curParent == null) {
return cur;
}else {
if (curParent.left != null && curParent.left.val == key) {
curParent.left = cur;
}else {
curParent.right = cur;
}
}
return root;
}
}
3 复杂度分析
时间复杂度:
空间复杂度:
4 涉及到知识点
5 总结
方法二 递归
1 方法思想
2 代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
//后序遍历
if (root == null) return root;
if (root.val > key){
root.left = deleteNode(root.left, key);
return root;
}
if (root.val < key){
root.right = deleteNode(root.right , key);
return root;
}
if (root.val == key){
if (root.left == null && root.right == null) return null;
if (root.left == null) return root.right;
if (root.right == null) return root.left;
TreeNode minRight = root.right;
while (minRight.left != null){
minRight = minRight.left;
}
root.right = deleteNode(root.right, minRight.val);
minRight.right = root.right;
minRight.left = root.left;
return minRight;
}
return root;
}
}
3 复杂度分析
时间复杂度:
空间复杂度: