二叉树的增加和查找
当你翻到这篇博客时,相信你对二叉树这种数据结构有一定的了解。通过二叉树对数据进行操作会比数组等数据结构优越的多。那么怎么对二叉树进行增删改查呢?
首先来介绍下二叉树的插入、查询、遍历。
因为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<p.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<a.length;i++) {
tree[i]=new Tree(a[i]);
tree[i].value=a[i];
}
init.insert(init, tree[0]);
for(int i=1;i<a.length;i++) {
init.insert(tree[0], tree[i]);
}
System.out.println("树初始化序列为:");
init.Bst(tree[0]);
}
遍历的话直接用递归或者非递归用栈来实现。这里用的是递归。
查找结点
public Tree Select(Tree root,int value) {
Tree flag=new Tree();
Stack<Tree> stack=new Stack<Tree>();
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的对象。
二叉树的删除和修改在下一篇博客 二叉树删除和修改