package search;
public class BinarySearchTree {
/**
* @param args
*/
public static void main(String[] args) {
int a[] = new int[] { 8,7,3,10,2,5,4,6 };
Node root = buildBinaryTree(a);
traverse(root);
// delet node
System.out.println("\nAfter delete:");
deleteTree(root, 3);
traverse(root);
}
public static void traverse(Node root) {
if (root == null) {
return;
}
traverse(root.left);
System.out.print(root.value + " ");
traverse(root.right);
}
public static Node buildBinaryTree(int a[]) {
// chose the first to be root. u can still randomly choose the
// first(root).
Node root = new Node(a[0], null, null, null);
for (int i = 1; i < a.length; i++) {
insertTree(root, a[i]);
}
return root;
}
// assume value is distinct
public static int deleteTree(Node root, int value) {
// -1 -> not find 0 -> OK
// get the Node
Node t = root;
boolean isleft = true;
boolean find = false;
while (t != null) {
if (t.value == value) {
find = true;
break;
} else if (t.value > value) {
t = t.left;
isleft = true;
} else {
t = t.right;
isleft = false;
}
}
// find one.
if (!find) {
return -1;
}
// if node has no child.
if (t.left == null && t.right == null) {
if (isleft)
{
t.parent.left = null;
}
else
{
t.parent.right=null;
}
t = null;
return 0;
}
if (t.left != null && t.right != null) {
// must be careful
// find the right minnum not null node.
Node r = t.right;
while (r.left != null) {
r = r.left;
}
// make sure the value
if (isleft) {
t.parent.left = r;
} else {
t.parent.right = r;
}
r.left = t.left;
r.right = t.right;
r.parent.left = null;
r.parent = t.parent;
t = null;
return 0;
}
// only one child.
if (t.left == null) {
t.parent.right = t.right;
t = null;
} else {
t.parent.left = t.left;
t = null;
}
return 0;
}
// root cann't be null.
public static void insertTree(Node root, int value) {
Node cur = root;
Node lastNode = null;
boolean useleft = true;
while (cur != null) {
lastNode = cur;
if (cur.value >= value) {
cur = cur.left;
useleft = true;
} else {
cur = cur.right;
useleft = false;
}
}
if (useleft) {
lastNode.left = new Node(value, null, null, lastNode);
} else {
lastNode.right = new Node(value, null, null, lastNode);
}
}
}
class Node {
Node left, right, parent;
int value;
public Node(int v) {
value = v;
}
public Node(int v, Node left, Node right, Node parent) {
value = v;
this.right = right;
this.left = left;
this.parent = parent;
}
public String toString() {
return (left == null ? null : left.value) + "," + (value) + ","
+ (right == null ? null : right.value);
}
}
删除分3种情况:
【1】左右节点都没空,则直接移除该节点。
【2】有一个子节点,则连接其子节点与其父节点
【3】有2个子节点,则找到该节点右子树中最左边的节点,替换。