590. N-ary Tree Postorder Traversal

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).

recursion DFS

/*
// 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> res = new ArrayList<>();
        dfs(root, res);
        return res;
    }
    private void dfs(Node node, List<Integer> list){
        if (node ==null) return;
        for(Node child : node.children){
            dfs(child,list);
        }
        list.add(node.val);
    }
}

Iteration

improvement using Linkedlist instead of Stack

Last updated

Was this helpful?