题目描述:
标签:树
给定一个 N 叉树,返回其节点值的 后序遍历 。
N 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值
null
分隔(请参见示例)。
代码:
思路分析:
思路同二叉树的后序遍历。不过就是递归的时候使用增强for循环遍历每一个子结点对他们进行后序递归。
/*
// 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;
}
};
*/
class Solution {
public List<Integer> postorder(Node root) {
List<Integer> list = new ArrayList<Integer>();
post(root,list);
return list;
}
public void post(Node root,List<Integer> res){
if(root == null){
return;
}
List<Node> nodes = root.children;
for(Node node : nodes){
post(node,res);
}
res.add(root.val);
}
}