Problem
Given an n-ary tree, return the preorder traversal of its nodes’ values.
For example, given a 3-ary tree:

Return its preorder traversal as: [1,3,5,6,2,4].
Note: Recursive solution is trivial, could you do it iteratively?
Solution1: Recursive
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua // Running time: 48 ms class Solution { public: vector<int> preorder(Node* root) { vector<int> ans; preorder(root, ans); return ans; } private: void preorder(Node* root, vector<int>& ans) { if (!root) return; ans.push_back(root->val); for (const auto& child : root->children) preorder(child, ans); } }; |
Solution2: Iterative
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Author: Huahua // Running time: 52 ms class Solution { public: vector<int> preorder(Node* root) { if (!root) return {}; vector<int> ans; stack<Node*> s; s.push(root); while (!s.empty()) { const Node* node = s.top(); s.pop(); ans.push_back(node->val); for (auto it = node->children.rbegin(); it != node->children.rend(); ++it) s.push(*it); } return ans; } }; |
We return the node with value 2, colored in yellow in the diagram.
The nodes colored in blue are the deepest nodes of the tree.
The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is a serialization of the given tree.
The output "[2, 7, 4]" is a serialization of the subtree rooted at the node with value 2.
Both the input and output have TreeNode type.

Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.
