450. Delete Node in a BST

删除二叉树节点,注意相等的时候删除中间节点的三步操作:找到最小值node,和root交换,删除那个node。

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 || root.right == null) {
            return (root.left != null) ? root.left : root.right; // return the subtree of deleted node 
        } 

        TreeNode min = findMin(root.right);
        root.val = min.val;
        root.right = deleteNode(root.right, min.val); // delete the node in the right side of the tree
    }
    return root;
}

public TreeNode findMin(TreeNode root) {
    while (root.left != null) {
        root = root.left;
    }
    return root;
}

results matching ""

    No results matching ""