public class BinaryTreeDemo {
public static void main(String args[]){
Employee emp1= new Employee(1,"李洛");
Employee emp2= new Employee(2,"张元清");
Employee emp3= new Employee(3,"牧尘");
Employee emp4= new Employee(4,"萧炎");
Employee emp5= new Employee(5,"许七安");
BinaryTree binaryTree =new BinaryTree(emp1);
emp1.setLeft(emp2);
emp1.setRight(emp3);
emp2.setLeft(emp4);
emp2.setRight(emp5);
binaryTree.preOrder();//12453
binaryTree.infixOrder();//42513
binaryTree.lastOrder();//45231
}
}
class BinaryTree{
private Employee root;
public BinaryTree(Employee root) {
this.root = root;
}
public Employee getRoot() {
return root;
}
public void setRoot(Employee root) {
this.root = root;
}
//前序遍历
public void preOrder(){
if (this.root!=null){
this.root.preOrder();
}else {
System.out.println("二叉树为空,无法遍历。");
}
}
//中序遍历
public void infixOrder(){
if (this.root!=null){
this.root.infixOrder();
}else{
System.out.println("二叉树为空,无法遍历。");
}
}
//后序遍历
public void lastOrder(){
if (this.root!=null){
this.root.lastOrder();
}else {
System.out.println("八嘎!");
}
}
}
class Employee{
private int id;
private String name;
private Employee left;
private Employee right;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Employee getLeft() {
return left;
}
public void setLeft(Employee left) {
this.left = left;
}
public Employee getRight() {
return right;
}
public void setRight(Employee right) {
this.right = right;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
//前序遍历
public void preOrder(){
System.out.println(this);
if(this.getLeft()!=null){
this.getLeft().preOrder();
}
if (this.getRight()!=null){
this.getRight().preOrder();
}
}
//中序遍历
public void infixOrder(){
if (this.left!=null){
this.left.infixOrder();
}
System.out.println(this);
if (this.right!=null){
this.right.infixOrder();
}
}
//后序遍历
public void lastOrder(){
if (this.left!=null){
this.left.lastOrder();
}
if (this.right!=null){
this.right.lastOrder();
}
System.out.println(this);
}
}
共勉!