Documentation IndexFetch the complete documentation index at: /llms.txtUse this file to discover all available pages before exploring further.
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 589 with 14 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 589 # by problem number lcpy gen -s n_ary_tree_preorder_traversal # by problem name
root
Input: root = [1,null,3,2,4,null,5,6] Output: [1,3,5,6,2,4]
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
from __future__ import annotations class NaryNode: def __init__(self, val: int = 0, children: list[NaryNode] | None = None) -> None: self.val = val self.children = children if children is not None else [] class Solution: # Time: O(n) # Space: O(n) def preorder(self, root: NaryNode | None) -> list[int]: if root is None: return [] result: list[int] = [] stack: list[NaryNode] = [root] while stack: node = stack.pop() result.append(node.val) stack.extend(reversed(node.children)) return result