Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created January 8, 2015 00:27
Show Gist options
  • Save kanrourou/ee1d89e6895c41ea735b to your computer and use it in GitHub Desktop.
Save kanrourou/ee1d89e6895c41ea735b to your computer and use it in GitHub Desktop.
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param value: Remove the node with given value.
* @return: The root of the binary search tree after removal.
*/
public TreeNode removeNode(TreeNode root, int value) {
if (root == null)
return null;
if (value < root.val)
root.left = removeNode(root.left, value);
else if (value > root.val)
root.right = removeNode(root.right, value);
else {
if (root.left == null)
return root.right;
if (root.right == null)
return root.left;
TreeNode x = root;
root = findMin(root.right);
root.right = deleteMin(x.right);
root.left = x.left;
}
return root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment