import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
*/
List<Integer> list = new ArrayList<>();
public int[][] threeOrders (TreeNode root) {
// write code here
preorder(root, list);
int[][] res = new int[3][list.size()];
for (int i=0; i<list.size(); i++) {
res[0][i] = list.get(i);
}
list.clear();
inorder(root, list);
for (int i=0; i<list.size();i++) {
res[1][i] = list.get(i);
}
list.clear();
postorder(root, list);
for (int i=0; i<list.size();i++) {
res[2][i] = list.get(i);
}
return res;
}
private void preorder(TreeNode root, List<Integer> list) {
if (root == null) return;
Stack<TreeNode> sk = new Stack<>();
sk.push(root);
while (!sk.isEmpty()) {
TreeNode node = sk.pop();
if (node.right != null) {
sk.push(node.right);
}
if (node.left != null) {
sk.push(node.left);
}
list.add(node.val);
}
//System.out.println(list);
}
private void inorder(TreeNode root, List<Integer> list) {
Stack<TreeNode> sk = new Stack<>();
while (!sk.isEmpty() || root != null) {
while (root != null) {
sk.push(root);
root = root.left;
}
TreeNode cur = sk.pop();
list.add(cur.val);
if (cur.right != null) {
root = cur.right;
}
}
}
private void postorder(TreeNode root, List<Integer> list) {
Stack<TreeNode> sk = new Stack<>();
TreeNode pre = null;
TreeNode cur = root;
while (!sk.isEmpty() || cur != null) {
while (cur != null) {
sk.push(cur);
cur = cur.left;
}
cur = sk.peek();
if(cur.right == null || cur.right == pre) { // 如果右子树为空 或者当前节点右节点 之前访问过
sk.pop();
list.add(cur.val);
pre = cur;
cur = null;
} else {
cur = cur.right;
}
}
}
}