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> l = new ArrayList<>(); dfs(root,l); return l; } public void dfs(Node root,List list) { if(root == null) return; root.children.forEach( h -> { dfs(h,list); }); list.add(root.val); } }
class Solution { public List<Integer> postorder(Node root) { Deque<Node> stack = new LinkedList<>(); if(root == null) return Collections.emptyList(); stack.push(root); LinkedList<Integer> list = new LinkedList<>(); while(stack.isEmpty() == false ) { Node parent = stack.pop(); parent.children.forEach(h -> { stack.push(h); }); list.addFirst(parent.val); } return list; } }