树集合了数组(查找速度快)和链表(插入、删除速度快)的优点
二叉树是一种特殊的树,即:树中的每个节点最多只能有两个子节点
二叉搜索树是一种特殊的二叉树,即:节点的左子节点的值都小于这个节点的值,节点的右子节点的值都大于等于这个节点的值
节点类:
public class Node {
public int id;
public String name;
public Node leftChild;
public Node rightChild;
public Node(int id, String name) {
this.id = id;
this.name = name;
}
}
实现类(如果树中允许存在重复数据,处理起来比较麻烦,故实现中不允许树中存在重复数据,即节点的右子节点的值必须大于节点的值):
搜索二叉树有一个特点,即如果使用中序遍历遍历搜索二叉树,将得到包含搜索二叉树中所有节点值的升序排序结果
public class BinarySearchTree {
public Node root;
public Node find(int key){
if(root == null){
System.out.println("The tree is empty!");
return null;
}
Node current = root;
while(current.id != key){
if(key > current.id)
current = current.rightChild;
else
current = current.leftChild;
if(current == null)
return null;
}
return current;
}
public boolean insert(Node node){
if(root == null){
root = node;
return true;
}
//树中不允许插入重复的数据项
if(this.find(node.id) != null){
System.out.println("Node with id '" +
node.id + "' has already existed!");
return false;
}
Node current = root;
while(current != null){
if(node.id > current.id){
if(current.rightChild == null){
current.rightChild = node;
return true;
}
current &#