跳转至

590. N-ary Tree Postorder Traversal

Leetcode Tree

Given an n-ary tree, return the postorder traversal of its nodes' values.

For example, given a 3-ary tree:

n-array-post-order

Return its postorder traversal as: [5,6,3,2,4,1].

Note:

  • Recursive solution is trivial, could you do it iteratively?

分析

public List<Integer> postorder(Node root) {
    List<Integer> list = new ArrayList<>();
    postorder(list, root);
    return list;
}

private void postorder(List<Integer> list, Node root) {
    if (root == null) return;
    for (Node node : root.children)
        postorder(list, node);
    list.add(root.val);
}