/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<Integer> postorder(Node root) {
List<Integer> list = new ArrayList<>();
if (root == null) return list;
if(root == null) return list;
Node node = root;
Stack<Node> stack1 = new Stack<>();
Stack<Node> stack2 = new Stack<>();
stack1.push(root);
while(!stack1.isEmpty()) {
node = stack1.pop();
stack2.add(node);
if(node.children != null) {
List<Node> c = node.children;
for(Node n:c) {
stack1.push(n);
}
}
}
while(!stack2.isEmpty()) {
list.add(stack2.pop().val);
}
return list;
}
public List<Integer> postorder2(Node root) {
List<Integer> list = new ArrayList<>();
if (root == null) return list;
Node node = null;
Node temp = null;
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
temp = stack.peek();
if (temp.children==null || (node!=null && temp.children.contains(node))) {
node = stack.pop();
list.add(node.val);
} else {
if (temp.children!=null) {
for (int i = temp.children.size()-1; i >= 0 ; i--) {
stack.push(temp.children.get(i));
}
}
}
}
return list;
}
}