题目
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:
Example 2:
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]
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
分析
题意:n叉树的后序遍历
思路:
只需要利用遍历“最小元”的思想进行递归即可。
n叉树后序遍历的最小元:遍历其他节点–>遍历根节点
从题意可知,根节点是root,其他节点是root.children中的节点。
因此算法就是,先递归遍历root.children的所有节点,再遍历根节点
解答
class Solution {
// 存放结果
List<Integer> list = new ArrayList<>();
public List<Integer> postorder(Node root) {
// 递归终点
if (root == null)
return list;
// 递归遍历其他节点
for(Node node: root.children)
postorder(node);
// 遍历根节点
list.add(root.val);
return list;
}
}