二叉树的前,中,后序遍历
public class BinaryTree {
public static void main(String[] args) {
Binary binary = new Binary();
Hero root = new Hero(1,"1");
Hero hero2 = new Hero(2, "2");
Hero hero3 = new Hero(3, "3");
Hero hero4 = new Hero(4, "4");
root.setLeft(hero2);
root.setRight(hero3);
hero3.setRight(hero4);
binary.setRoot(root);
//前序遍历
System.out.println("前序遍历");
binary.pre();
//中序遍历
System.out.println("中序遍历");
binary.infix();
//后序遍历
System.out.println("后序遍历");
binary.last();
}
}
class Binary{
private Hero root;
public Hero getRoot() {
return root;
}
public void setRoot(Hero root) {
this.root = root;
}
//前序遍历
public void pre() {
if(root!=null) {
root.pre();
}else {
System.out.println("二叉树为空,无法遍历");
}
}
//中序遍历
public void infix() {
if(root!=null) {
root.infix();
}else {
System.out.println("二叉树为空,无法遍历");
}
}
//后序遍历
public void last() {
if(root!=null) {
root.last();
}else {
System.out.println("二叉树为空,无法遍历");
}
}
}
class Hero{
private int no;
private String name;
private Hero left;
private Hero right;
public Hero(int no,String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Hero getLeft() {
return left;
}
public void setLeft(Hero left) {
this.left = left;
}
public Hero getRight() {
return right;
}
public void setRight(Hero right) {
this.right = right;
}
@Override
public String toString() {
return "Hero [no=" + no + ", name=" + name + "]";
}
public void pre() {
System.out.println(this);
if(this.left!=null) {
this.left.pre();
}
if(this.right!=null) {
this.right.pre();
}
}
public void infix() {
if(this.left!=null) {
this.left.infix();
}
System.out.println(this);
if(this.right!=null) {
this.right.infix();
}
}
public void last() {
if(this.left!=null) {
this.left.last();
}
if(this.right!=null) {
this.right.last();
}
System.out.println(this);
}
}