KatInterview

764. N-ary Tree Level Order Traversal

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for a level order traversal of an N-ary tree. This means we need to visit all nodes at the same depth (or level) from left to right, before moving on to the nodes at the next level. The output should be a list of lists, where each inner list contains the node values for one level.

Solution

N-ary Tree Level Order Traversal in Python

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""
import collections
from typing import List, Optional

class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        # Handle the edge case of an empty tree.
        if not root:
            return []

        result = []
        # Use a deque (double-ended queue) for efficient appends and pops from both ends.
        q = collections.deque([root])

        while q:
            # Get the number of nodes at the current level.
            level_size = len(q)
            current_level = []

            # Process all nodes at the current level.
            for _ in range(level_size):
                node = q.popleft()
                current_level.append(node.val)
                
                # Add all children of the current node to the queue for the next level.
                if node.children:
                    q.extend(node.children)
            
            # Add the completed level to the result.
            result.append(current_level)
            
        return result

N-ary Tree Level Order Traversal in Java

/*
// 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;
    }
};
*/

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        // Handle the edge case of an empty tree.
        if (root == null) {
            return result;
        }

        // Use a queue for Breadth-First Search.
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            // Get the number of nodes at the current level.
            int levelSize = queue.size();
            List<Integer> currentLevel = new ArrayList<>();

            // Process all nodes at the current level.
            for (int i = 0; i < levelSize; i++) {
                Node node = queue.poll();
                currentLevel.add(node.val);

                // Add all children of the current node to the queue for the next level.
                for (Node child : node.children) {
                    queue.add(child);
                }
            }
            // Add the completed level to the result.
            result.add(currentLevel);
        }

        return result;
    }
}

N-ary Tree Level Order Traversal in C++

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

#include <vector>
#include <queue>

class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        vector<vector<int>> result;
        // Handle the edge case of an empty tree.
        if (root == nullptr) {
            return result;
        }

        // Use a queue for Breadth-First Search.
        queue<Node*> q;
        q.push(root);

        while (!q.empty()) {
            // Get the number of nodes at the current level.
            int levelSize = q.size();
            vector<int> currentLevel;
            
            // Process all nodes at the current level.
            for (int i = 0; i < levelSize; ++i) {
                Node* node = q.front();
                q.pop();
                currentLevel.push_back(node->val);
                
                // Add all children of the current node to the queue for the next level.
                for (Node* child : node->children) {
                    q.push(child);
                }
            }
            // Add the completed level to the result.
            result.push_back(currentLevel);
        }

        return result;
    }
};

N-ary Tree Level Order Traversal in TypeScript

/**
 * Definition for _Node.
 * class _Node {
 *     val: number
 *     children: _Node[]
 *     
 *     constructor(v: number) {
 *         this.val = v;
 *         this.children = [];
 *     }
 * }
 */

function levelOrder(root: _Node | null): number[][] {
	// Handle the edge case of an empty tree.
    if (!root) {
        return [];
    }

    const result: number[][] = [];
    // Use an array as a queue for Breadth-First Search.
    const queue: _Node[] = [root];

    while (queue.length > 0) {
        // Get the number of nodes at the current level.
        const levelSize = queue.length;
        const currentLevel: number[] = [];
        
        // Process all nodes at the current level.
        for (let i = 0; i < levelSize; i++) {
            // shift() removes the first element and returns it.
            // The ! is a non-null assertion operator, telling TypeScript that we know this won't be undefined.
            const node = queue.shift()!;
            currentLevel.push(node.val);
            
            // Add all children of the current node to the queue for the next level.
            for (const child of node.children) {
                queue.push(child);
            }
        }
        // Add the completed level to the result.
        result.push(currentLevel);
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.