解题思路:
分五种情况
- 找不到删除节点
- 删除节点为叶子节点
- 删除节点左为空,右不为空
- 删除节点右为空,左不为空
- 删除节点左右都不为空(最核心的处理逻辑)
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
return recur(root, key);
}
public TreeNode recur(TreeNode root, int key) {
if (root == null) return null;
if (root.val == key) {
if (root.left == null && root.right == null) return null;
else if (root.left == null && root.right != null) return root.right;
else if (root.left != null && root.right == null) return root.left;
else {
TreeNode cur = root.right;
while (cur.left != null) cur = cur.left;
cur.left = root.left;
return root.right;
}
}
root.left = recur(root.left, key);
root.right = recur(root.right, key);
return root;
}
}