congr / world

2 stars 1 forks source link

LeetCode : 450. Delete Node in a BST #524

Closed congr closed 5 years ago

congr commented 5 years ago

image image

congr commented 5 years ago
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
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 { // found
            if (root.right == null && root.left == null) return null;
            else if (root.right == null) return root.left;
            else if (root.left == null) return root.right;
            else { // left && right exist
                root.val = getMin(root.right);                
                root.right = deleteNode(root.right, root.val);
            }
        }

        return root;
    }

    int getMin(TreeNode root) {
        while (root.left != null) root = root.left; // !! root.left != null
        return root.val;
    }
}