java 二叉树查询_java二叉排序树增删改查

二叉树的增加和查找

当你翻到这篇博客时,相信你对二叉树这种数据结构有一定的了解。通过二叉树对数据进行操作会比数组等数据结构优越的多。那么怎么对二叉树进行增删改查呢?

首先来介绍下二叉树的插入、查询、遍历。

因为java面向对象,我们就把每个结点当作对象处理。

这个对象应该有value数值。指向左右孩子结点的对象,把整棵树连接起来。然后有一个指向自己的父结点,方便删除操作。

tree类定义:public class Tree {

public int value;

public Tree parent;

public Tree left;

public Tree right;

public Tree() {};

public Tree(int value) {

this.value=value;

}

这里把value等属性设置成了public,设置成private比较好。这样只对类的对象可见。通过getter和setter操作。为了省事,我把它设置成了public。望读者理解。

添加结点(insert):public Tree insert(Tree root,Tree p) {

if(root==null) {

root=p;

root.parent=null;

return root;

}

Tree temp=new Tree();

temp=root;

while(temp!=null) {

if(temp.value

if(temp.right!=null) {

temp=temp.right;

}

else {

temp.right=new Tree();

temp.right.value=p.value;

temp.right.parent=temp;

break;}

}

if(temp.value>p.value) {

if(temp.left!=null) {

temp=temp.left;

}

else{

temp.left=new Tree();

temp.left.value=p.value;

temp.left.parent=temp;

break;

}

}

}

return root;

}

插入函数传递的参数是两个Tree对象,第一个是树的根结点,第二个是要插入的结点。当插入完第一个结点之后,每次插入的时候都从根结点往下走。比根节点小,走左边。根节点更新为左边的结点。比根节点大,走右边。根节点更新为右边的结点。直到左边或者右边为空,new一下,插入就ok了。

遍历结点(Bst):public void Bst(Tree root) {

if(root!=null) {

Bst(root.left);

System.out.print(root.value+" ");

Bst(root.right);

}

}

主函数调用public static void main(String[] args) {

// TODO Auto-generated method stub

int []a= {20,8,2,4,5,6,28,18,19,33,25,26};

Tree init=new Tree(100);

Tree []tree=new Tree[a.length];

for(int i=0;i

tree[i]=new Tree(a[i]);

tree[i].value=a[i];

}

init.insert(init, tree[0]);

for(int i=1;i

init.insert(tree[0], tree[i]);

}

System.out.println("树初始化序列为:");

init.Bst(tree[0]);

}

1042

遍历的话直接用递归或者非递归用栈来实现。这里用的是递归。

查找结点public Tree Select(Tree root,int value) {

Tree flag=new Tree();

Stack stack=new Stack();

while(!stack.empty()||root!=null)

{

if(root!=null) {

if(root.value==value)

{

flag=root;

}

stack.push(root);

root=root.left;

}

else {

root=stack.pop();

if(root.value==value)

{

flag=root;

}

root=root.right;

}

}

return flag;

}

查找函数传递的参数是根结点和要查找的数值。

此时也应该遍历一下整棵树。注意不能用递归,因为用递归不能返回找到的结点。用栈来实现遍历。返回值为obj.value==value的对象。

二叉树的删除和修改在下一篇博客 二叉树删除和修改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值