java实现二叉排序树的生成、查找、打印

直接上代码:

public class Test {
public static void main(String args[]) {
int[] data = {6,4,9,1,8,5,3,7};          //初始化data数组备用
TreeNode[] TreeNodeList = new TreeNode[data.length];  //建立TreeNode数组存储树的结点
int i;
for(i=0; i<data.length; i++) {            //初始化一系列结点
TreeNodeList[i] = new TreeNode(data[i]);
}                                                            
TreeNode root = new TreeNode();         //声明一个根节点
root.data = data[0];                              //将data数组的第一个元素设置为根结点的值
try {                                                     //下面时捕获异常,debug用
for(i=1; i<TreeNodeList.length; i++) {
root.BstInsert(TreeNodeList[i].data);
System.out.println("number: " + i + " data: " + TreeNodeList[i].data);
}
} catch(NullPointerException e) {
e.printStackTrace();
}
root.print();                //先序遍历打印二叉树
root.BstSearch(9);          //查询元素9

}
}
//创建树的结点的类
class TreeNode {
public int data ;
public TreeNode lchild = null;
public TreeNode rchild = null;

public TreeNode() {
}
public TreeNode(int data) {
this.data = data;
}


public void print() {
if(this == null) System.out.println("end");
else {
System.out.println(this.data);
if(this.lchild!=null) this.lchild.print();        //递归打印左孩子,注意一定要进行null判断,否则会出现NulPointerException异常
if(this.rchild!=null) this.rchild.print();       //递归打印右孩子
}
}
public TreeNode BstSearch(int n) {
if(this.data == n) {
System.out.println("you have find it");
return this;
}
else if(n < this.data)
return this.lchild.BstSearch(n);       //递归调用
else return this.rchild.BstSearch(n);
}


public int BstInsert(int n) {
if(this.data == n) return 0;
else if(n < this.data) {
System.out.println("left");
if(this.lchild == null) {           //这里一定要判断,否则会出现NullPointer异常
this.lchild = new TreeNode();
this.lchild.data = n;
}
else return this.lchild.BstInsert(n);
}
else {
System.out.println("right");
if(this.rchild == null) {
this.rchild = new TreeNode();
this.rchild.data = n;
}
else return this.rchild.BstInsert(n);
}
return 0;
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值