题目描述
Given an n-ary tree, return the postorder traversal of its nodes’ values.
For example, given a 3-ary tree:
Return its postorder traversal as: [5,6,3,2,4,1].
Note:
Recursive solution is trivial, could you do it iteratively?
方法思路
Approach1: recursive
class Solution {
//Runtime: 2 ms, faster than 100.00%
//Memory Usage: 46.7 MB, less than 80.42%
List<Integer> res = new ArrayList<>();
public List<Integer> postorder(Node root) {
if(root == null) return res;
for(Node child : root.children)
postorder(child);
res.add(root.val);
return res;
}
}
Approach2: iteratively
class Solution {
//Runtime: 6 ms, faster than 34.74%
public List<Integer> postorder(Node root) {
List<Integer> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
stack.add(root);
while(!stack.isEmpty()){
root = stack.pop();
list.add(root.val);
for(Node node : root.children)
stack.push(node);
}
Collections.reverse(list);
return list;
}
}
方法2的优化:
用LinkedList会更加方便,毕竟可以直接添加到头部,不需要反转列表了。
class Solution {
public List<Integer> postorder(Node root) {
LinkedList<Integer> list = new LinkedList();
if(root == null) return list;
Stack<Node> s = new Stack();
s.push(root);
while(!s.isEmpty()) {
Node temp = s.pop();
list.addFirst(temp.val);
for(Node n : temp.children) {
s.push(n);
}
}
return list;
}
}