二叉排序树_Java简单实现

来源:互联网 发布:网络布控中心 编辑:程序博客网 时间:2024/05/22 07:40

动态查找过程中需要进行插入和删除操作,如果采用线性表顺序存储的话,这些操作很费时,因此二叉排序树是一个很好的解决方案。

二叉排序树(也成为二叉查找树),具有下列性质:如果它的左子树不空,则左子树上所有节点的值均小于它的根节点的值;如果它的右子树不空,则右子树上的所有节点的值均小于它的更节点的值,下面是一个Java程序实现的二叉查找树。


package search;


class Node<T> {
private T value;


public T getValue() {
return value;
}


public void setValue(T value) {
this.value = value;
}


public Node<T> getL_child() {
return l_child;
}


public void setL_child(Node<T> l_child) {
this.l_child = l_child;
}


public Node<T> getR_child() {
return r_child;
}


public void setR_child(Node<T> r_child) {
this.r_child = r_child;
}


private Node<T> l_child;
private Node<T> r_child;


public Node() {


}


public Node(T t) {
value = t;
}


}


public class BinarySearch {


// test main method
public static void main(String[] args) {
int[] array = { 19, 12, 3, 22, 6, 7, 21, 11, 43 };
Node<Integer> root = new Node<Integer>(array[0]);
for (int i = 1; i < array.length; i++) {
binarySort(root, array[i]);
}


// look this binary tree
inOrderTraverse(root);


if (binarySerach(root, 12)) {
System.out.println("二叉树中存在此元素");
} else {
System.out.println("二叉树中不存在该元素");
}
}


// 二叉排序树插入操作
public static void binarySort(Node<Integer> root, int key) {


int value = root.getValue();


if (key < value) {
if (root.getL_child() == null) {
Node<Integer> r = new Node<Integer>(key);
root.setL_child(r);
} else {
binarySort(root.getL_child(), key);
}
} else {
if (root.getR_child() == null) {
Node<Integer> r = new Node<Integer>(key);
root.setR_child(r);
} else {
binarySort(root.getR_child(), key);
}
}
}


public static boolean binarySerach(Node<Integer> root, int key) {
if (root == null) {
// throw new NullPointerException();
return false;
} else if (root.getValue() == key) {
return true;
} else if (root.getValue() < key) {
return binarySerach(root.getR_child(), key);
} else {
return binarySerach(root.getL_child(), key);
}
}


//中序遍历
public static void inOrderTraverse(Node<Integer> root) {
if (root == null) {
return;
}
inOrderTraverse(root.getL_child());
System.out.println(root.getValue());
inOrderTraverse(root.getR_child());
}


}


0 0
原创粉丝点击