删除BST中的一个节点,我起初写了非常复杂的版本,考虑了很多种情况。还错了很多次。。
直接看大佬的代码吧
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (key > root.val) root.right = deleteNode(root.right, key);
else if (key < root.val) root.left = deleteNode(root.left, key);
else {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
TreeNode tmp = root.left;
while (tmp.right != null) tmp = tmp.right;
tmp.right = root.right;
return root.left;
}
return root;
}