package com.example.ljia.Structure.tree;
import lombok.Data;
/**
* @ Author :SamLai
* @ Description:递归 二叉树 先序遍历 中序遍历 后续遍历
* 先序遍历 :根 左 右
* 中序遍历 :左 根 右
* 后序遍历 :左 右 根
* 发现规律:这里的顺序是根节点为核心来的
* 原理:
* 利用函数栈来保存信息的
*
* 以一棵树为例:
* 1
* 2 3
* 4 5 6
*
打印结果:
前序遍历 :
1 2 4 5 3 6
中序遍历 :
4 2 5 1 3 6
后序遍历 :
4 5 2 6 3 1
*
*/
@Data
public class Node {
private int value;
private Node left;
private Node right;
public Node(int value) {
this.value = value;
}
/**
* 前序
* @param head
*/
public static void preOrderRecur(Node head) {
if (head == null) {
return;
}
System.out.print(head.getValue() + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
/**
* 中序
* @param head
*/
public static void inOrderRecur(Node head) {
if (head == null) {
return;
}
inOrderRecur(head.left);
System.out.print(head.getValue() + " ");
inOrderRecur(head.right);
}
/**
* 后序
* @param head
*/
public static void posOrderRecur(Node head) {
if (head == null) {
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.getValue() + " ");
}
public static void main(String[] args) {
/**
* 以一棵树为例:
* 1
* 2 3
* 4 5 6
*/
Node head = new Node(1);
Node left1 = new Node(2);
Node right1 = new Node(3);
head.setLeft(left1);
head.setRight(right1);
Node left2 = new Node(4);
Node right2 = new Node(5);
left1.setLeft(left2);
left1.setRight(right2);
Node right3 = new Node(6);
right1.setRight(right3);
System.out.println("前序遍历 : ");
preOrderRecur(head);
System.out.println();
System.out.println("中序遍历 : ");
inOrderRecur(head);
System.out.println();
System.out.println("后序遍历 : ");
posOrderRecur(head);
/**
*
打印结果:
前序遍历 :
1 2 4 5 3 6
中序遍历 :
4 2 5 1 3 6
后序遍历 :
4 5 2 6 3 1
*
*/
}
}