N-ary Tree Preorder Traversal

Easy

Description

Given the root of an n-ary tree, return the preorder traversal of its nodes values. Preorder visits the root first, then all children from left to right.

Examples

Input:root = [1,null,3,2,4,null,5,6]
Output:[1,3,5,6,2,4]
Explanation:

Preorder: root, then children.

Input:root = []
Output:[]
Explanation:

Empty tree case: when the root is null/empty, preorder traversal returns an empty array since there are no nodes to visit.

Input:root = [7,null,2,9,1,8,null,null,6]
Output:[7,2,6,9,1,8]
Explanation:

Preorder traversal visits root first (7), then recursively visits each child's subtree from left to right: first child 2 and its child 6, then second child 9, then third child 1, and finally fourth child 8.

Constraints

  • 0 ≤ nodes ≤ 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!