import java.util.*;
public class Solution {
public int[][] threeOrders (TreeNode root) {
// 三个集合,分别存储三种遍历结果
List<Integer> list1 = new ArrayList<>(); // 先序结果
List<Integer> list2 = new ArrayList<>(); // 中序结果
List<Integer> list3 = new ArrayList<>(); // 后序结果
// 分别调用对应的函数
preOrder(root,list1);
inOrder(root,list2);
postOrder(root,list3);
// 构建结果集并返回
int[][] ans = new int[3][list1.size()];
for (int i = 0; i < list1.size(); i++) {
ans[0][i] = list1.get(i);
ans[1][i] = list2.get(i);
ans[2][i] = list3.get(i);
}
return ans;
}
// 先序遍历函数
public static void preOrder(TreeNode root, List<Integer> list1) {
// 预处理
if (root == null) return;
// 对左右子树进行递归遍历
list1.add(root.val); // 根
preOrder(root.left, list1); // 左
preOrder(root.right, list1); // 右
}
// 中序遍历函数
public static void inOrder(TreeNode root, List<Integer> list2) {
// 预处理
if (root == null) return;
// 对左右子树进行递归遍历
inOrder(root.left, list2); // 左
list2.add(root.val); // 根
inOrder(root.right, list2); // 右
}
// 后序遍历函数
public static void postOrder(TreeNode root, List<Integer> list3) {
// 预处理
if (root == null) return;
// 对左右子树进行递归遍历
postOrder(root.left, list3); // 左
postOrder(root.right, list3); // 右
list3.add(root.val); // 根
}
}