//定义节点及遍历方法
@Data
public class HeroNode {
private Integer id;
private String name;
private HeroNode left;
private HeroNode right;
public HeroNode(Integer id, String name) {
this.id = id;
this.name = name;
}
/**
* 前序遍历
*/
public void preList(){
//先输出当前节点
System.out.print(this.id);
//判断左边有节点,则左边递归进行前序遍历
if(this.left != null){
this.left.preList();
}
//判断右边有节点,则右边递归进行前序遍历
if(this.right != null){
this.right.preList();
}
}
/**
* 中序遍历
*/
public void midList(){
//判断左边有节点,则左边递归进行前序遍历
if(this.left != null){
this.left.midList();
}
//输出当前节点
System.out.print(this.id);
//判断右边有节点,则右边递归进行前序遍历
if(this.right != null){
this.right.midList();
}
}
/**
* 后序遍历
*/
public void postList(){
//判断左边有节点,则左边递归进行前序遍历
if(this.left != null){
this.left.postList();
}
//判断右边有节点,则右边递归进行前序遍历
if(this.right != null){
this.right.postList();
}
//输出当前节点
System.out.print(this.id);
}
}
//二叉树
@Data
public class BinaryTree {
private HeroNode head;
/**
* 前序遍历
*/
public void preList(){
if(head != null){
head.preList();
}else{
System.out.println("二叉树为空");
}
}
/**
* 中序遍历
*/
public void midList(){
if(head != null){
head.midList();
}else{
System.out.println("二叉树为空");
}
}
/**
* 后序遍历
*/
public void postList(){
if(head != null){
head.postList();
}else{
System.out.println("二叉树为空");
}
}
}
//测试
public class BinaryTreeDemo {
public static void main(String[] args) {
HeroNode heroNode1 = new HeroNode(1,"一号");
HeroNode heroNode2 = new HeroNode(2,"二号");
HeroNode heroNode3 = new HeroNode(3,"一号");
HeroNode heroNode4 = new HeroNode(4,"一号");
HeroNode heroNode5 = new HeroNode(5,"一号");
//创建一个二叉树
BinaryTree binaryTree = new BinaryTree();
binaryTree.setHead(heroNode1);
heroNode1.setLeft(heroNode2);
heroNode1.setRight(heroNode3);
heroNode3.setLeft(heroNode5);
heroNode3.setRight(heroNode4);
//遍历
System.out.println("前序:");
binaryTree.preList();
System.out.println();
System.out.println("中序:");
binaryTree.midList();
System.out.println();
System.out.println("后序:");
binaryTree.postList();
}
}
结果:
前序:
12354
中序:
21534
后序:
25431
树的遍历
最新推荐文章于 2023-03-14 17:04:32 发布