Thinking process
- find the node
- if left subtree doesn't exist, return the right child
- if right child, return the left child;
- if the node has two children, then set the node's value to the minimum value in its right subtree and then delete that minimum value.
public class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (root.val > key) root.left = deleteNode(root.left, key);
else if (root.val < key) root.right = deleteNode(root.right, key);
else {
if (root.left == null) return root.right;
else if (root.right == null) return root.left;
root.val = getMinOfRight(root.right);
root.right = deleteNode(root.right, root.val);
}
return root;
}
private int getMinOfRight(TreeNode root) {
while (root.left != null) {
root = root.left;
}
return root.val;
}
}