public class BinarySearchTree {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode parent;
TreeNode(int x) {
val = x;
}
}
public class Tree {
TreeNode root;
public Tree(TreeNode root) {
this.root = root;
}
}
public TreeNode search(TreeNode x, int k) {
if (x == null || x.val == k)
return x;
if (k < x.val) {
return search(x.left, k);
}
return search(x.right, k);
}
public TreeNode iterativeSearch(TreeNode x, int k) {
while (x != null && x.val != k) {
if (k < x.val)
x = x.left;
else
x = x.right;
}
return x;
}
public TreeNode minimum(TreeNode x) {
if (x == null)
return x;
while (x.left != null) {
x = x.left;
}
return x;
}
public TreeNode maximum(TreeNode x) {
if (x == null)
return x;
while (x.right != null) {
x = x.right;
}
return x;
}
public TreeNode successor(TreeNode x) {
if (x == null)
return x;
while (x.right != null)
return minimum(x.right);
TreeNode p = x.parent;
while (p != null && x == p.right) {
x = p;
p = p.parent;
}
return p;
}
public TreeNode predecessor(TreeNode x) {
if (x == null)
return x;
while (x.left != null)
return maximum(x.left);
TreeNode p = x.parent;
while (p != null && x == p.left) {
x = p;
p = p.parent;
}
return p;
}
public void insert(Tree t, TreeNode z) {
TreeNode p = null, x = t.root;
while (x != null) {
p = x;
if (z.val < x.val) {
x = x.left;
} else {
x = x.right;
}
}
z.parent = p;
if (p == null) {
t.root = z;
} else if (z.val < p.val) {
p.left = z;
} else {
p.right = z;
}
}
private void transplant(Tree t, TreeNode u, TreeNode v) {
if (u.parent == null)
t.root = v;
else if (u == u.parent.left) {
u.parent.left = v;
} else
u.parent.right = v;
if (v != null)
v.parent = u.parent;
}
public void delete(Tree t, TreeNode z) {
if (z.left == null) {
transplant(t, z, z.right);
} else if (z.right == null) {
transplant(t, z, z.left);
} else {
TreeNode y = minimum(z.right);
if (y.parent != z) {
transplant(t, y, y.right);
y.right = z.right;
y.right.parent = y;
}
transplant(t, z, y);
y.left = z.left;
y.left.parent = y;
}
}
}