java查找二叉树中的元素以及确定位置
发布网友
发布时间:2022-04-19 19:43
我来回答
共2个回答
热心网友
时间:2023-07-09 02:14
//二叉树结构类 Btree.java
public class Btree {
private int data;
private Btree left;
private Btree right;
public void setData(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setLeft(Btree btree) {
this.left = btree;
}
public void setRight(Btree btree) {
this.right = btree;
}
public Btree getLeft() {
return left;
}
public Btree getRight() {
return right;
}
public Btree() {
super();
}
}
//工具类,二叉树创建,查找,遍历,排序。都在这了 Tools.java
public class Tools {
public Btree create(int data) {
Btree btree = new Btree();
btree.setData(data);
return btree;
}
public void add(Btree btree, int data) {
if (data < btree.getData()) {
if (btree.getLeft() != null) {
btree = btree.getLeft();
add(btree, data);
} else {
btree.setLeft(create(data));
}
} else {
if (btree.getRight() != null) {
btree = btree.getRight();
add(btree, data);
} else {
btree.setRight(create(data));
}
}
}
//中序遍历
public void midSerch(Btree btree) {
if (btree.getLeft() != null)
midSerch(btree.getLeft());
System.out.print(btree.getData()+" ");
if (btree.getRight() != null)
midSerch(btree.getRight());
}
//二叉树查找
public void find(Btree btree ,int data){
if(btree.getData()>data)
{
if(btree.getLeft()==null)
{
System.out.println("没有这种结果,搜索完毕");
return;
}else
find(btree.getLeft(),data);
}else if(btree.getData()==data)
{
System.out.println("查找成功,查找到的数据是"+data);
return;
}else
{
if(btree.getRight()==null){
System.out.println("没有这种结果,搜索完毕");
return;
}
else
find(btree.getRight(),data);
}
}
}
//主类,与注释的自己看 MidSerchBtree.java
public class MidSerchBtree {
public static void main(String args[]) {
Tools tools = new Tools();
int datas[] = { 6, 4, 3, 7, 8, 9, 2, 1, 5,8,9,12,23,45,3,7,5 };
Btree btree = tools.create(datas[0]);
for (int i = 1; i < datas.length; i++) {//第一个初始化插入作为根节点了
tools.add(btree, datas[i]);
}
tools.midSerch(btree);//中根遍历 小的插入左边,大的在右边,所以,中序遍历一遍就是排序
tools.find(btree, 56);
}
}
热心网友
时间:2023-07-09 02:15
很多答案啊,自己找就好了。百度搜索:二叉排序树 java