}
控制台的输出如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210325140448550.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ3NDcxMzg1,size_16,color_FFFFFF,t_70#pic_center)
## 2.二叉树的中序遍历
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210325120425917.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ3NDcxMzg1,size_16,color_FFFFFF,t_70#pic_center)
package jichu;
/**中序遍历:中根次序遍历,顺序:左根右(先打印左支树,根节点,右支树)如图输出:4,2,5,1,3,6
* 后序遍历:后根次序遍历,顺序:左右根*/
public class TreeNode {
private int value;//表示节点的值
private TreeNode left;//左支树
private TreeNode right;//右支数
//构造方法
public TreeNode(){}
public TreeNode(int value){
this.value = value;
}
//设计一个方法用中序遍历的方法,打印二叉树
public static void minRoot(TreeNode root){
if (root == null){
return;
}else {
//先打印左支树
minRoot(root.left);
//打印根节点
System.out.println(root.value);
//打印右支树
minRoot(root.right);
}
}
public static void main(String[] args) {
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
node3.right = node6;
//firstRoot(node1);
minRoot(node1);
}
}
控制台输出如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210325140226588.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ3NDcxMzg1,size_16,color_FFFFFF,t_70#pic_center)
## 3.二叉树的后序遍历
package jichu;
/** 后序遍历:后根次序遍历,顺序:左右根(先打印左支树,右支树,根节点)如图上输出:4,5,2,6,3,1*/
public class TreeNode {
private int value;//表示节点的值
private TreeNode left;//左支树
private TreeNode right;//右支数
//构造方法
public TreeNode(){}
public TreeNode(int value){
this.value = value;
}
//设计一个方法用后序遍历的方法,输出二叉树
public static void lastRoot(TreeNode root){
if (root ==null){
return;
}else {
//输出左支树
lastRoot(root.left);
//输出右支树
lastRoot(root.right);
//输出根节点
System.out.print(root.value);
}
}
public static void main(String[] args) {
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
node3.right = node6;
lastRoot(node1);
}
}
控制台输出结果如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210325142928553.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ3NDcxMzg1,size_16,color_FFFFFF,t_70#pic_center)**总结:**
>
> **前序遍历:先根次序遍历,顺序:根左右(根,左支树,右支树)如图上输出:1,2,4,5,3,6
> 中序遍历:中根次序遍历,顺序:左根右(先打印左支树,根节点,右支树)如图上输出:4,2,5,1,3,6
> 后序遍历:后根次序遍历,顺序:左右根(先打印左支树,右支树,根节点)如图上输出:4,5,2,6,3,1**
>
>
>
**留言:欢迎小伙伴们的评论 ~**