[LeetCode] 590. N-ary Tree Postorder Traversal

Given 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).

Follow up:

Recursive solution is trivial, could you do it iteratively?

Example 1:

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

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 height of the n-ary tree is less than or equal to 1000
  • The total number of nodes is between [0, 10^4]

N叉树的后序遍历。题目即是题意。题目的followup依然是问是否能用迭代的做法实现。我这里把迭代和递归的做法都练习了一下。

迭代

思路还是很直观的,既然是后序遍历,那么遍历的顺序自然就是左 - 右 - 根,转换到多叉树就是孩子 - 根。联想到二叉树的后序遍历需要用到stack,所以这里也需要用到stack,并且将孩子节点放入的时候还是按正常顺序放,所以弹出的时候就是逆序的。每个节点放入结果集的时候依然是从res的头部开始放。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public List<Integer> postorder(Node root) {
 3         LinkedList<Integer> res = new LinkedList<>();
 4         // corner case
 5         if (root == null) {
 6             return res;
 7         }
 8 
 9         // normal case
10         Stack<Node> stack = new Stack<>();
11         stack.push(root);
12         while (!stack.isEmpty()) {
13             Node cur = stack.pop();
14             res.addFirst(cur.val);
15             for (Node child : cur.children) {
16                 stack.push(child);
17             }
18         }
19         return res;
20     }
21 }

递归

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     List<Integer> list = new ArrayList<>();
 3     
 4     public List<Integer> postorder(Node root) {
 5         // corner case
 6         if (root == null) {
 7             return list;
 8         }
 9 
10         // normal case
11         for (Node node : root.children) {
12             postorder(node);
13         }
14         list.add(root.val);
15         return list;
16     }
17 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13494155.html