在数据结构中,二叉树的三种遍历方式分别如下:
前序遍历:根 左 右
中序遍历:左 根 右
后序遍历:左 右 根
Java实现代码如下:
//二叉树类
public class BiT2ree {
private int data;
private BiT2ree left;
private BiT2ree right;
public BiT2ree(int x)
{
data = x;
}
//二叉排序树
public void add(BiT2ree x){
if(x.data < this.data){
if(left == null)
left = x;
else
left.add(x);
}
else{
if(right == null)
right = x;
else
right.add(x);
}
}
//实现前序排序
public void pre(){
if(this != null){
System.out.println(this.data);
}
if(left != null)
left.pre();
if(right !=null)
right.pre();
}
//实现中序遍历
public void display(){
if(left != null)
left.display();
System.out.println(data);
if(right !=null)
right.display();
// System.out.println(data);
}
//实现后续排序
public void af(){
if(left != null)
left.af();
if(right != null)
right.af();
System.out.println(this.data);
}
}
//测试代码类
public class BiTreeTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BiT2ree t = new BiT2ree(12);
t.add(new BiT2ree(8));
t.add(new BiT2ree(5));
t.add(new BiT2ree(15));
t.add(new BiT2ree(9));
t.add(new BiT2ree(20));
//中序排序
t.display();
//前序排序
System.out.println(" ");
t.pre();
//后序排序
System.out.println(" ");
t.af();
}
}
代码可以正常运行。。