概述
二叉树遍历(前中后序遍历)
![](https://img-blog.csdnimg.cn/5026e8b0b37f4a0485c599558bbfaa68.png)
![](https://img-blog.csdnimg.cn/2340276dfcbe4076a858f2b55cd1ea3b.png)
思路
代码
public class BinaryTreeDemo {
public static void main(String[] args) {
//先需要创建一颗二叉树
BinaryTree binaryTree = new BinaryTree();
//创建需要的结点
HeroPoint root = new HeroPoint(1, "宋江");
HeroPoint node2 = new HeroPoint(2, "吴用");
HeroPoint node3 = new HeroPoint(3, "卢俊义");
HeroPoint node4 = new HeroPoint(4, "林冲");
HeroPoint node5 = new HeroPoint(5, "关胜");
//先手动创建该二叉树,后面递归的方式创建二叉树
root.setLeft(node2);
root.setRight(node3);
node3.setRight(node4);
node3.setLeft(node5);
binaryTree.setRoot(root);
//测试
System.out.println("前序遍历"); // 1,2,3,5,4
binaryTree.perSortByRoot();
System.out.println("中序遍历");
binaryTree.centerSortByRoot(); // 2,1,5,3,4
System.out.println("后序遍历");
binaryTree.finalSortByRoot(); // 2,5,4,3,1
}
}
class BinaryTree{
private HeroPoint root;
public void setRoot(HeroPoint root) {
this.root = root;
}
public void perSortByRoot(){
if (this.root != null){
this.root.perSort();
}else {
System.out.println("前序遍历失败, 二叉树为空");
}
}
public void centerSortByRoot(){
if (this.root != null){
this.root.centSort();
}else {
System.out.println("中序遍历失败, 二叉树为空");
}
}
public void finalSortByRoot(){
if (this.root != null){
this.root.finalSort();
}else {
System.out.println("前序遍历失败, 二叉树为空");
}
}
}
class HeroPoint{
private int id;
private String name;
private HeroPoint left;
private HeroPoint right;
public void perSort(){
//输出
System.out.println(this);
//左遍历输出左节点
if(this.left != null){
this.left.perSort();
}
//右遍历输出右节点
if(this.right != null){
this.right.perSort();
}
}
public void centSort(){
//左遍历输出左节点
if(this.left != null){
this.left.centSort();
}
//输出序号
System.out.println(this);
//右遍历输出右节点
if(this.right != null){
this.right.centSort();
}
}
public void finalSort(){
//左遍历输出左节点
if(this.left != null){
this.left.finalSort();
}
//右遍历输出右节点
if(this.right != null){
this.right.finalSort();
}
//输出序号
System.out.println(this);
}
get/set/toString方法
public HeroPoint(int id, String name) {
this.id = id;
this.name = name;
}
}