Simple Java solution


  • 2
    T
        public TreeNode deleteNode(TreeNode root, int key) {
            if (root == null) {
                return root;
            }
    
            if (root.val > key) {
                root.left = deleteNode(root.left, key);
            } else if (root.val < key) {
                root.right = deleteNode(root.right, key);
            } else { //Delete Case
     
                // First condition where node is last node
                if (root.left == null && root.right == null) {
                    root = null;
                } 
                
                // 2nd case where it has either left node or right node
                else if (root.right == null) {
                    root = root.left;
                } else if (root.left == null) {
                    root = root.right;
                } else {
                    //3rd case
                    TreeNode node = rightModeMinNode(root.right);
                    deleteNode(root, node.val);
                    root.val = node.val;
    
                }
            }
            return root;
        }
        
    	TreeNode rightModeMinNode(TreeNode node) {
    		if (node == null) {
    			return null;
    		}
    
    		if (node.left == null) {
    			return node;
    		}
    
    		return rightModeMinNode(node.left);
    	}
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.