https://leetcode.com/problems/delete-node-in-a-bst/
删除BST中的指定节点
如果当前节点为要删除的,可以把左子节点或者右子节点移动上来,模块化即可
public class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
// 有可能要删除的点不存在
if (root == null) {
return null;
}
if (root.val == key) {
return adjust(root);
} else if (root.val > key) {
root.left = deleteNode(root.left, key);
} else {
root.right = deleteNode(root.right, key);
}
return root;
}
private TreeNode adjust(TreeNode root) {
TreeNode ret = null;
if (root.left != null) {
ret = root.left;
TreeNode rightest = getRight(root.left);
rightest.right = root.right;
} else if (root.right != null) {
ret = root.right;
TreeNode leftest = getLeft(root.right);
leftest.left = root.left;
}
return ret;
}
private TreeNode getRight(TreeNode root) {
while (root.right != null) {
root = root.right;
}
return root;
}
private TreeNode getLeft(TreeNode root) {
while (root.left != null) {
root = root.left;
}
return root;
}
}