给定一个 N 叉树,返回其节点值的 后序遍历 。
N 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。
进阶:
递归法很简单,你可以使用迭代法完成此题吗?
示例 1:
输入:root = [1,null,3,2,4,null,5,6]
输出:[5,6,3,2,4,1]
示例 2:
输入: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]
输出:[2,6,14,11,7,3,12,8,4,13,9,10,5,1]
提示:
N 叉树的高度小于或等于 1000
节点总数在范围 [0, 10^4] 内
class Solution {/**dfs求解*/List<Integer> res = new ArrayList<>();public List<Integer> postorder(Node root) {if (root == null) return res;dfs(root);//最后加上root.valres.add(root.val);return res;}public void dfs(Node root) {if (root == null) return;for (Node child : root.children) {dfs(child);res.add(child.val);}}}
class Solution {public List<Integer> postorder(Node root) {List<Integer> res = new ArrayList<>();if (root == null) return res;Deque<Node> stack = new LinkedList<>();stack.push(root);while (!stack.isEmpty()) {Node node = stack.poll();res.add(node.val);for (Node child : node.children) {stack.push(child);}}//前序遍历是 根左右 上边是根右左 所以需要翻转一下数组即为后序遍历Collections.reverse(res);return res;}}
