给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树
:
返回其后序遍历: [5,6,3,2,4,1]
.
/**
* 590. N叉树的后序遍历
* https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/
*
* @param root
* @return
*/
public List<Integer> postorder(Node root) {
if (root == null) {
return Collections.emptyList();
}
List<Integer> res = new ArrayList<>();
add(root, res);
return res;
}
private void add(Node root, List<Integer> list) {
if (root == null) {
return;
}
List<Node> children = root.children;
if (children != null && !children.isEmpty()) {
for (Node child : children) {
add(child, list);
}
}
list.add(root.val);
}