KatInterview

775. N-ary Tree Preorder Traversal

EasySolutions 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

Method: Iterative Approach using a Stack

This problem asks for the preorder traversal of an N-ary tree. A preorder traversal visits the current node first, then traverses its children from left to right. The standard recursive solution is trivial, but the follow-up question prompts for an iterative solution. We can achieve this using a stack to explicitly manage the nodes to visit, mimicking the behavior of the call stack in recursion.

Solution

N-ary Tree Preorder 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
"""

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        if not root:
            return []

        # Use a list as a stack for iterative traversal
        stack = [root]
        result = []

        while stack:
            # Pop the top node and add its value to the result
            node = stack.pop()
            result.append(node.val)

            # Add children to the stack in reverse order (right to left)
            # so they are processed from left to right.
            # The [::-1] slice creates a reversed copy of the children list.
            if node.children:
                stack.extend(node.children[::-1])
                
        return result

N-ary Tree Preorder 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;
    }
};
*/

class Solution {
    public List<Integer> preorder(Node root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        // Use a stack for iterative traversal
        Stack<Node> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            // Pop the top node and add its value to the result
            Node current = stack.pop();
            result.add(current.val);

            // Push children onto the stack in reverse order (right to left)
            // so that they are processed from left to right.
            // Using Collections.reverse would also work but is less efficient.
            for (int i = current.children.size() - 1; i >= 0; i--) {
                if (current.children.get(i) != null) {
                    stack.push(current.children.get(i));
                }
            }
        }

        return result;
    }
}

N-ary Tree Preorder 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;
    }
};
*/

class Solution {
public:
    vector<int> preorder(Node* root) {
        vector<int> result;
        if (root == nullptr) {
            return result;
        }

        // Use a stack for iterative traversal
        stack<Node*> nodeStack;
        nodeStack.push(root);

        while (!nodeStack.empty()) {
            // Pop the top node and add its value to the result
            Node* current = nodeStack.top();
            nodeStack.pop();
            result.push_back(current->val);

            // Push children onto the stack in reverse order (right to left)
            // so that they are processed from left to right.
            for (int i = current->children.size() - 1; i >= 0; --i) {
                if (current->children[i] != nullptr) {
                    nodeStack.push(current->children[i]);
                }
            }
        }

        return result;
    }
};

N-ary Tree Preorder Traversal in TypeScript

/**
 * Definition for _Node.
 * class _Node {
 *     val: number
 *     children: _Node[]
 * 
 *     constructor(val?: number, children?: _Node[]) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.children = (children===undefined ? [] : children)
 *     }
 * }
 */

function preorder(root: _Node | null): number[] {
    if (!root) {
        return [];
    }

    // Use an array as a stack for iterative traversal
    const stack: _Node[] = [root];
    const result: number[] = [];

    while (stack.length > 0) {
        // Pop the top node and add its value to the result.
        // The non-null assertion `!` is safe because we check `stack.length > 0`.
        const node = stack.pop()!;
        result.push(node.val);

        // Push children onto the stack in reverse order (right to left)
        // so they are processed from left to right.
        for (let i = node.children.length - 1; i >= 0; i--) {
            if (node.children[i]) {
                stack.push(node.children[i]);
            }
        }
    }

    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.