=> reverse ( use linkedList addFirst(), ๆณจๆ่ฆ็จ้ๅ่ฆ้ ญๅฐพ้ฝๅฎฃๅ็ด LinkedList<> list = new LinkedList<>() ๆๆๆ้ๅๆนๆณ
=>ๅพๅฐ็ญๆก
O(M), O(M) M is the total nodes of this tree
classSolution {publicList<Integer> postorder(Node root) {// because preorder is root left right// postorder is left right root// so root right left then reverse is postorder// to acheive reverse we can push (addFirst) to LinkedListLinkedList<Integer> res =newLinkedList<>();if (root ==null) {return res; }Stack<Node> stack =newStack<>();stack.add(root);while (!stack.isEmpty()) {Node node =stack.pop(); // pop right then leftif (node !=null) {res.addFirst(node.val); // add first, so it would be left right rootfor (Node n :node.children) {stack.push(n); // push left right } } }return res; }}
recursive
/*// 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; }};*/classSolution {publicList<Integer> postorder(Node root) {List<Integer> res =newArrayList<>();helper(root, res);return res; }privatevoidhelper(Node root,List<Integer> res) {if (root ==null) {return; }for (Node node :root.children) {helper(node, res); }res.add(root.val); }}