思路:
// @Title: 删除二叉搜索树中的节点 (Delete Node in a BST)
// @Author: qisiii
// @Date: 2024-09-16 17:32:48
// @Runtime: 0 ms
// @Memory: 44.9 MB
// @comment:
// @flag:
/**
* 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 {
TreeNode parent;
public TreeNode deleteNode(TreeNode root, int key) {
if(root==null){
return null;
}
if (root.val == key) {
//左右任意节点为空
if (root.left == null || root.right == null) {
return root.left == null ? root.right : root.left;
}else{
TreeNode cur=root.right;
while(cur.left!=null){
cur=cur.left;
}
cur.left=root.left;
return root.right;
}
} else if (root.val > key) {
root.left = deleteNode(root.left, key);
} else {
root.right = deleteNode(root.right, key);
}
return root;
}
}