您的位置:首页 > 其它

二叉树遍历算法

2013-08-02 17:31 253 查看
二叉树是一种非线性的数据结构,在对它进行操作时,总是需要逐一对每个数据元素实施操作,这样就存在一个操作顺序问题,由此提出了二叉树的遍历操作。所谓遍历二叉树就是按某种顺序访问二叉树中的每个结点一次且仅一次的过程。这里的访问可以是输出、比较、更新、查看元素内容等等各种操作。

在这里写了个二叉树遍历算法、根据三种不同的顺序得到三种不同的顺序结果、

public class BinaryTree {

int data;
BinaryTree left = null;
BinaryTree right = null;

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

public void insert(BinaryTree root,int data){//二叉树中插入子结点

if(data<root.data){//二叉树左结点比根结点小

if(root.left!=null){
insert(root.left, data);
}else{
root.left = new BinaryTree(data);
}
}else{//二叉树右结点比根结点大
if(root.right!=null){
insert(root.right, data);
}else{
root.right = new BinaryTree(data);
}

}
}

/**
*
* @param root
* @param order 遍历顺序
* 1 先序	(根结点——>左结点——>右结点)
* 2 中序	(左结点——>根结点——>右结点)
* 3 后序	(左结点——>右结点——>根结点)
*/
public static void order(BinaryTree root ,int order){

switch (order) {
case 1://先序

if(root!=null){
System.out.print(root.data+" --> ");
order(root.left,order);
order(root.right,order);
}

break;
case 2://中序

if(root!=null){
order(root.left,order);
System.out.print(root.data+" --> ");
order(root.right,order);
}

break;
case 3://后序

if(root!=null){
order(root.left,order);
order(root.right,order);
System.out.print(root.data+" --> ");
}

break;

default:
break;
}
}

public static void main(String[] args) {

int[] ints = {1,22,3,44,5,66,7,88,9,11};
BinaryTree root = new BinaryTree(ints[0]);   //创建二叉树
for(int i=1;i<ints.length;i++){
root.insert(root, ints[i]);       //向二叉树中插入数据
}
System.out.println("\n先序遍历:");
order(root, 1);
System.out.println("\n中序遍历:");
order(root, 2);
System.out.println("\n后序遍历:");
order(root, 3);
}

}


打印结果如下:

先序遍历:
1 --> 22 --> 3 --> 5 --> 7 --> 9 --> 11 --> 44 --> 66 --> 88 -->
中序遍历:
1 --> 3 --> 5 --> 7 --> 9 --> 11 --> 22 --> 44 --> 66 --> 88 -->
后序遍历:
11 --> 9 --> 7 --> 5 --> 3 --> 88 --> 66 --> 44 --> 22 --> 1 -->
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: