[Programming Problem] N-ary Tree Level Order Traversal

Given an n-ary tree, return the level order traversal of its nodes’ values.

[Problem Link]

Pretty straightforward BFS traversal logic. Here are some small gotcha’s:

  • Add condition for empty/undefined input.
  • When you return the list of lists, the expectation is to return just values and not the Node object. Notice the last line (ret.map(..)) is doing just that.
/**
 * // Definition for a Node.
 * function Node(val,children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */
/**
 * @param {Node} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    if ( !root || root.length === 0) return [];
    let ret = [[root]];
    let currLevel = 0;
    while (true) {
        let nextLevel = [];
        ret[currLevel].forEach((item) => item.children.forEach((child) => nextLevel.push(child))); 
        if ( nextLevel.length === 0 ) break;
        ret.push(nextLevel);
        currLevel++;
    }    
    return ret.map((arr) => arr.map((item) => item.val))
};

Leave a Reply

Your email address will not be published. Required fields are marked *