请用语句创建二叉树存储结构,并实现二叉树的前序,中序,后序遍历。
分享一段作业代码
先创建出一个学生类 StudentNode 写出遍历方法
package shu;
public class StudentNode{
public int id;
public String name;
public int cj;
public StudentNode left; //默认null
public StudentNode right;
public StudentNode(int id, String name,int cj) {
this.id = id;
this.name = name;
this.cj=cj;
}
@Override
public String toString() {
return "学生信息{" +
"学号=" + id +
", 姓名='" + name + '\'' +
", 成绩=" + cj +
'}';
}
//前序遍历
public void preOrder(){
System.out.println(this);
if (this.left!=null){
this.left.preOrder();
}
if (this.right!=null){
this.right.preOrder();
}
}
//中序遍历
public void inOrder(){
if (this.left!=null){
this.left.inOrder();
}
System.out.println(this);
if (this.right!=null){
this.right.inOrder();
}
}
//后续遍历
public void postOrder(){
if (this.left!=null){
this.left.postOrder();
}
if (this.right!=null){
this.right.postOrder();
}
System.out.println(this);
}
}
定义二叉树,创建BinaryTree类:
package shu;
//定义二叉树
public class BinaryTree{
public StudentNode root;
public void setRoot(StudentNode root) {
this.root = root;
}
//前序遍历
public void preOrder(){
if (this.root!=null){
this.root.preOrder();
}else {
System.out.println("为空,无法遍历");
}
}
//中序遍历
public void inOrder(){
if (this.root!=null){
this.root.inOrder();
}else {
System.out.println("为空,无法遍历");
}
}
//后续遍历
public void postOrder(){
if (this.root!=null){
this.root.postOrder();
}else {
System.out.println("为空,无法遍历");
}
}
}
定义测试类Demo
package shu;
public class Demo {
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
StudentNode root = new StudentNode(2020, "干果",88);
StudentNode no2 = new StudentNode(2021, "藤原松瘪",99);
StudentNode no3 = new StudentNode(2022, "鼹神",99);
StudentNode no4 = new StudentNode(2023, "赖瘪",95);
StudentNode no5 = new StudentNode(2024, "少爷",96);
root.left=no2;
root.right=no3;
no2.left=no4;
no2.right=no5;
binaryTree.setRoot(root);
System.out.println("前序遍历:");
binaryTree.preOrder();
System.out.println("\n中序遍历:");
binaryTree.inOrder();
System.out.println("\n后续遍历:");
binaryTree.postOrder();
}
}
运行结果