DEV Community

codingpineapple
codingpineapple

Posted on

589. N-ary Tree Preorder Traversal

Description:

Given an n-ary tree, return the preorder 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)

var preorder = function(root, output = []) {
    // If we start with no root or we reach a null value return the output
    if(!root) return output;
    // Add the current root val to the output on each call
    output.push(root.val)
    // Repeat for all of the root's children
    for(const child of root.children) {
        preorder(child, output);
    }
    return output;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)