590. N-ary Tree Postorder Traversal

Given the root of an n-ary tree, return the postorder traversal of its nodes’ values.

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

Example 1:
Example 1
Input: root = [1,null,3,2,4,null,5,6]
Output: [5,6,3,2,4,1]

Example 2:
Example 2
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]

Constraints:
The number of nodes in the tree is in the range [0, 104].
0 <= Node.val <= 104
The height of the n-ary tree is less than or equal to 1000.

Follow up: Recursive solution is trivial, could you do it iteratively?

N 叉树的后序遍历。

给定一个 n 叉树的根节点 root ,返回 其节点值的 后序遍历 。
n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。

思路

题目的 followup 依然是问是否能用迭代的做法实现。我这里把迭代和递归的做法都练习了一下。

复杂度

迭代和递归的做法复杂度一样
时间O(n)
空间O(n)

迭代代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public List<Integer> postorder(Node root) {
List<Integer> res = new ArrayList<>();
// corner case
if (root == null) {
return res;
}

// normal case
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node cur = stack.pop();
res.add(0, cur.val);
if (cur.children != null) {
for (Node child : cur.children) {
stack.push(child);
}
}
}
return res;
}
}

递归代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<Integer> postorder(Node root) {
List<Integer> res = new ArrayList<>();
// corner case
if (root == null) {
return res;
}
helper(res, root);
return res;
}

private void helper(List<Integer> res, Node root) {
if (root == null) {
return;
}
for (Node child : root.children) {
helper(res, child);
}
res.add(root.val);
}
}

590. N-ary Tree Postorder Traversal
https://shurui91.github.io/posts/3703104611.html
Author
Aaron Liu
Posted on
August 13, 2020
Licensed under