java 二叉排序_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

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

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());

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值