遍历二叉树

package A;

import java.util.Scanner;

public class JosePhu {
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();

Emp root=new Emp(1,"zml");
Emp node2=new Emp(2,"zml2");
Emp node3=new Emp(3,"zml3");
Emp node4=new Emp(4,"zml4");
Emp node5=new Emp(5,"zml5");
Emp node6=new Emp(6,"zml6");
Emp node7=new Emp(7,"zml7");

root.setLeft(node2);
root.setRight(node3);
node2.setLeft(node4);
node2.setRight(node5);
node3.setLeft(node6);
node3.setRight(node7);

binaryTree.setRoot(root);
binaryTree.qian();
System.out.println("=======");
binaryTree.zhong();
System.out.println("===========");
binaryTree.hou();
}
}

/*
* 写盒子该有的东西,比如id,name。因为我看人家一般用private,所以我也用了,但是用了private就要写get,set方法
* 写一个有参构造器
* 实现get,set方法
* 重写toString方法*/
class Emp {//盒子部分
private int id;//任何的private都需要get,set方法
private String name;
private Emp left;
private Emp right;

public Emp(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 Emp getLeft() {
return left;
}

public void setLeft(Emp left) {
this.left = left;
}

public Emp getRight() {
return right;
}

public void setRight(Emp right) {
this.right = right;
}

@Override
public String toString() {
return "Emp{" +
"id=" + id +
", 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 suffixOrder(){
if (this.left!=null){
this.left.suffixOrder();
}
if (this.right!=null){
this.right.suffixOrder();
}

System.out.println(this);
}
}

class BinaryTree {
//这其实跟哈希表一样的结构
private Emp root;

public void setRoot(Emp root) {
this.root = root;
}

public void qian() {
if (this.root != null) {
this.root.preOrder();
} else {
System.out.println("empty");
}
}

public void zhong() {
if (this.root != null) {
this.root.midOrder();
} else {
System.out.println("empty");
}
}

public void hou() {
if (this.root != null) {
this.root.suffixOrder();
} else {
System.out.println("empty");
}
}
}



遍历二叉树

上一篇:web学习笔记——CSS整理(一)


下一篇:核函数方法