Java实现二叉排序树

/**
* 二叉树排序--将一个整型数组中的元素存进二叉排序树中再查找元素;
* @author luliangy
*
*/
public class BTsort {

public static void main(String[] args) {

//自定义一个整型的数组;
int[] array={19,12,3,22,6,7,21,11,43};

//创建根节点;

Node root=new Node(array[0]);

//依次将数组中的元素插入
for(int i=1;i<array.length;i++){
BinarySort(root,array[i]);
}

//查找指定的元素;
if(BinarySerch(root,12)){
System.out.println("二叉树中存在此元素");
}else{
System.out.println("二叉树中不存在该元素");
}

//遍历指定的二叉树并输出--采用中序遍历法;
inOrder(root);

}

/**
* 将指定的元素插入二叉排序树中
* @param root
* @param key
*/
public static void BinarySort(Node root,int key){

//得到根节点中的元素;
int value = root.getKey();
//判断该插入左子树还是右子树;
if(key<value){//插入柚子树
if(root.getLeft()==null){
Node node=new Node(key);
root.setLeft(node);
}else{
BinarySort(root.getLeft(),key);
}

}else if(key>value){
if(root.getRight()==null){
Node node=new Node(key);
root.setRight(node);
}else{
BinarySort(root.getRight(),key);
}
}
}

/**
* 二叉树搜索树;
* @param root
* @param key
*/
public static boolean BinarySerch(Node root,int key){
if(root==null){
return false;
}else if(root.getKey()==key){
return true;
}else if(root.getKey()>key){
return BinarySerch(root.getLeft(),key);
}else{
return BinarySerch(root.getRight(),key);
}
}

/**
* 采用中序遍历法遍历一个二叉树
* @param root
*/
public static void inOrder(Node root){
if(root!=null){
inOrder(root.getLeft());
root.visitNode();
inOrder(root.getRight());
}
}

}

原文地址:https://www.cnblogs.com/cy19/p/8186564.html