1、假设二叉树的结点值是字符型,根据输入的一棵二叉树的完整先序遍历序列(子树空用’#’表示),建立一棵以二叉链表存储表示的二叉树。
2、对二叉树进行先序、中序和后序遍历操作,并输出遍历序列,观察输出的序列是否与逻辑上的序列一致。
3、主程序中要求设计一个菜单,允许用户通过菜单来多次选择执行哪一种遍历操作。
4、主程序最后输出个人的学号和姓名。
你好!输入1,2,3返回不同遍历
public class StudentNode {
public int id;
public String name;
public int fs;
public StudentNode left; //默认null
public StudentNode right;
public StudentNode(int id, String name,int fs) {
this.id = id;
this.name = name;
this.fs=fs;
}
@Override
public String toString() {
return "学生{" +
"id=" + id +
", name='" + name + '\'' +
", fs=" + fs +
'}';
}
//前序遍历
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);
}
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("为空,无法遍历");
}
}
import java.util.*;
public class Demo {
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
StudentNode root = new StudentNode(1, "a",96);
StudentNode no2 = new StudentNode(2, "b",99);
StudentNode no3 = new StudentNode(3, "c",80);
StudentNode no4 = new StudentNode(4, "d",85);
StudentNode no5 = new StudentNode(5, "e",96);
root.left=no2;
root.right=no3;
no2.left=no4;
no2.right=no5;
binaryTree.setRoot(root);
Scanner cin =new Scanner(System.in);
int t=cin.nextInt();
if(t==1){
System.out.println("前序遍历:");
binaryTree.preOrder();
}else if(t==2){
System.out.println("\n中序遍历:");
binaryTree.inOrder();
}else{
System.out.println("\n后续遍历:");
binaryTree.postOrder();
}
}
非线性结构-二叉树
https://blog.csdn.net/jikui0581/article/details/106229686
二叉树的常见问题及其解决思路
https://blog.csdn.net/liukun321/article/details/46537997
你是要提供程序代码还是什么?