分别进行先序、中序和后序遍历,将遍历结果加入最终结果即可
import java.util.*;
public class Solution {
public int[][] threeOrders (TreeNode root) {
ArrayList<Integer> preRes = new ArrayList<>();
ArrayList<Integer> inRes = new ArrayList<>();
ArrayList<Integer> postRes = new ArrayList<>();
preRes = preOrder(root,preRes);
inRes = inOrder(root,inRes);
postRes = postOrder(root,postRes);
int[][] res = new int[3][];
res[0] = preRes.stream().mapToInt(Integer::intValue).toArray();
res[1] = inRes.stream().mapToInt(Integer::intValue).toArray();
res[2] = postRes.stream().mapToInt(Integer::intValue).toArray();
return res;
}
public ArrayList preOrder(TreeNode root,ArrayList preRes){
if(root == null){
return preRes;
}
preRes.add(root.val);
preOrder(root.left,preRes);
preOrder(root.right,preRes);
return preRes;
}
public ArrayList inOrder(TreeNode root,ArrayList inRes){
if(root == null){
return inRes;
}
inOrder(root.left,inRes);
inRes.add(root.val);
inOrder(root.right,inRes);
return inRes;
}
public ArrayList postOrder(TreeNode root,ArrayList postRes){
if(root == null){
return postRes;
}
postOrder(root.left,postRes);
postOrder(root.right,postRes);
postRes.add(root.val);
return postRes;
}
}