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类
* @return int整型一维数组
*/
public int[] postorderTraversal (TreeNode root) {
// write code here
if (root == null) {
return new int[0];
}
List<Integer> list = new LinkedList<>();
TreeNode pre = null;
Stack<TreeNode> stack = new Stack<>();
//设置一个前驱节点
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
//如果没有到左子树最底下的点,继续入栈
}
//取出最后一个元素,就是我们的后序遍历的第一个元素
root = stack.pop();
if (root.right != null && root.right != pre) {
stack.push(root);
root = root.right;
//我们这个点不空,然后且不是上一个节点,我们继续入栈
} else {
System.out.println(root.val);
list.add(root.val);
pre = root;
root = null;
}
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
}