[leetCode]590. N叉树的后序遍历
题目
https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/
给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树 :
返回其后序遍历: [5,6,3,2,4,1].
递归
class Solution {
List<Integer> ans = new ArrayList();
public List<Integer> postorder(Node root) {
traversal(root);
return ans;
}
private void traversal(Node node) {
if (node == null)
return;
for (Node c : node.children) {
traversal(c);
}
ans.add(node.val);
}
}
迭代
class Solution {
List<Integer> ans = new ArrayList();
public List<Integer> postorder(Node root) {
if (root == null) return ans;
LinkedList<Node> stack = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
Node node = stack.pop();
if (node != null) {
stack.push(node);
stack.push(null);
for (int i = node.children.size() - 1; i >= 0; i--) { // 左后进所以左先出
if (node.children.get(i) != null)
stack.push(node.children.get(i) );
}
} else {
Node cur = stack.pop();
ans.add(cur.val);
}
}
return ans;
}
}