Java 二叉树前序、中序、后序三种遍历

在数据结构中,二叉树的三种遍历方式分别如下:

前序遍历:根 左 右

中序遍历:左 根 右

后序遍历:左 右 根

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();
	}

}
代码可以正常运行。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值