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