java二叉树的遍历

二叉树顾名思义只有两个分支,而对于二叉树的遍历存在前序,中序,后序,对于前序,其顺序为从根节点到左子树再到右子树,中序为左子树到根节点再到右子树,后序为左子树到右子树再到根节点。为了遍历方便,这里使用回溯算法。

class  binarytree
{
	private heronode root;
	public void setroot(heronode root)
	{
		this.root=root;
	}
	public void preorder()
	{
		if(this.root!=null)
		{
			this.root.preorder();
		}
		else
		{
			System.out.println("二叉树为空,无法遍历");
		}
	}
	public void midorder()
	{
		if(this.root!=null)
		{
			this.root.midorder();
		}
		else
		{
			System.out.println("二叉树为空,无法遍历");
		}
	}
	public void postorder()
	{
		if(this.root!=null)
		{
			this.root.postorder();
		}
		else
		{
			System.out.println("二叉树为空,无法遍历");
		}
	}
}
class heronode
{
	private int no;
	String name;
	heronode left;
	heronode right;
	public heronode(int id,String name)
	{
		this.name=name;
		this.no=id;
	}
	public int getno()
	{
		return no;
	}
	public void setno(int id)
	{
		this.no=id;
	}
	public String getname()
	{
		return name;
	}
	public void setname(String name)
	{
		this.name=name;
	}
	public heronode getleft()
	{
		return left;
	}
	public void setno(heronode left)
	{
		this.left=left;
	}
	public heronode getright()
	{
		return right;
	}
	public void setright(heronode right)
	{
		this.right=right;
	}
	@Override
	public String toString() {
		return "heronode [no=" + no + ", name=" + name + "]";
	}
	public void preorder()
	{
		System.out.println(this);
		if(this.left!=null)
		{
			this.left.preorder();
		}
		if(this.right!=null)
		{
			this.right.preorder();
		}
	}
	public void midorder()
	{
		if(this.left!=null)
		{
			this.left.midorder();
		}
		System.out.println(this);
		if(this.right!=null)
		{
			this.right.midorder();
		}
	}
	public void postorder()
	{
		if(this.left!=null)
		{
			this.left.postorder();
		}
		if(this.right!=null)
		{
			this.right.postorder();
		}
		System.out.println(this);
		
	}

}
public class binarytreedemo {

	public static void main(String[] args) {
		binarytree tree = new binarytree();
		heronode root = new heronode(1,"tom");
		heronode node2 = new heronode(2,"lee");
		heronode node3 = new heronode(3,"kitty");
		heronode node4 = new heronode(4,"anni");
		root.left=node2;
		root.right=node3;
		node3.right=node4;
		tree.setroot(root);
		System.out.println("前序遍历是:");
		tree.preorder();
		System.out.println("中序遍历是:");
		tree.midorder();
		System.out.println("后序遍历是:");
		tree.postorder();
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值