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;
}
}

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/M15717126343/article/details/79509057
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞