# 二叉树的前、中、后序排列

```import lombok.*;

/**
* @author: Small sunshine
* @Description：
* @date: 2021/6/30 8:05 下午
*/
public class SortTree {

public static void main(String[] args) {
Tree treeG = new Tree(‘G‘, null, null);
Tree treeD = new Tree(‘D‘, null, null);
Tree treeF = new Tree(‘F‘, null, null);
Tree treeE = new Tree(‘E‘, treeF, null);
Tree treeB = new Tree(‘B‘, treeD, treeE);
Tree treeC = new Tree(‘C‘, treeG, null);
Tree treeA = new Tree(‘A‘, treeB, treeC);
//前序排列
System.out.print("前序排列：");
VLR(treeA);
System.out.println();
//中序排列
System.out.print("中序排列：");
LDR(treeA);
System.out.println();
//后序排列
System.out.print("后序排列：");
LRD(treeA);
System.out.println();

}

/**
* 输出节点
*
* @param tree
*/
public static void print(Tree tree) {
System.out.print(tree.getData());
}

/**
* 前序排列-VLR
*
* @param tree
*/
public static void VLR(Tree tree) {
print(tree);
if (tree.left != null) {
VLR(tree.left);
}
if (tree.right != null) {
VLR(tree.right);
}
}

/**
* 中序排序-LDR
*
* @param tree
*/
public static void LDR(Tree tree) {
if (tree.left != null) {
LDR(tree.left);
}
print(tree);
if (tree.right != null) {
LDR(tree.right);
}
}

/**
* 后序排列-LRD
*
* @param tree
*/
public static void LRD(Tree tree) {
if (tree.left != null) {
LRD(tree.left);
}
if (tree.right != null) {
LRD(tree.right);
}
print(tree);
}

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public static class Tree {
private char data;
private Tree left;
private Tree right;
}
}
```

(0)
(0)

© 2014 mamicode.com 版权所有