public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public TreeNode findLeftMax(TreeNode root) {
while (root.right != null) {
root = root.right;
}
return root;
}
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
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) {
return root.right;
}
if (root.right == null) {
return root.left;
}
TreeNode tp = findLeftMax(root.left);
root.val = tp.val;
root.left = deleteNode(root.left, root.val);
}
return root;
}
LeetCode 450.Delete Node in a BST
最新推荐文章于 2023-05-03 22:46:32 发布