Bootstrap

力扣 LeetCode 450. 删除二叉搜索树中的节点(Day11:二叉树)

解题思路:

分五种情况

  1. 找不到删除节点
  2. 删除节点为叶子节点
  3. 删除节点左为空,右不为空
  4. 删除节点右为空,左不为空
  5. 删除节点左右都不为空(最核心的处理逻辑)
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;
    }
}

;