題目
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;
}
}