450.Delete Node in a BST

1

/**
 * 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{
            //root.val = key
            if(root.left == null)
                return root.right;
            else if(root.right == null)
                return root.left;
            else{
                TreeNode rightSmallest = root.right;
                while(rightSmallest.left != null){
                    rightSmallest = rightSmallest.left;
                }

                rightSmallest.left = root.left;
                return root.right;
            }
        }
        return root;
    }
}

results matching ""

    No results matching ""