DEV Community

codingpineapple
codingpineapple

Posted on

590. N-ary Tree Postorder Traversal (javscript soution)

Description:

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

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

// Create an output array to hold the order of nodes
// Add all child nodes before you any root node
var postorder = function(root) {
    const result = []
    function traverse(node, result) {
        if(!node) return;
        for(const child of node.children) traverse(child, result)
        result.push(node.val)
    }
    traverse(root, result)
    return result;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)