--- tags: leetcode --- # [589. N-ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal/) --- # My Solution ## Solution 1: recursive algorithm ### The Key Idea for Solving This Coding Question ### C++ Code ```cpp= /* // 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> answer; dfs(root, answer); return answer; } private: void dfs(Node *root, vector<int> &answer) { if (root == nullptr) { return; } answer.push_back(root->val); for (Node *next : root->children) { dfs(next, answer); } } }; ``` ### Time Complexity $O(n)$ $n$ is the number of nodes in the n-ary tree referred by `root`. ### Space Complexity $O(H)$ $H$ is the height the n-ary tree referred by `root`. ## Solution 2: Iteration and stack ### The Key Idea for Solving This Coding Question ### C++ Code ```cpp= /* // 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) { if (root == nullptr) { return {}; } vector<int> answer; stack<Node *> st; st.push(root); while (!st.empty()) { Node *node = st.top(); st.pop(); answer.push_back(node->val); for (int i = node->children.size() - 1; i >= 0; --i) { if (node->children[i] != nullptr) { st.push(node->children[i]); } } } return answer; } }; ``` ### Time Complexity $O(n)$ $n$ is the number of nodes in the n-ary tree referred by `root`. ### Space Complexity $O(H)$ $H$ is the height the n-ary tree referred by `root`. # Miscellane <!-- # Test Cases ``` [1,null,3,2,4,null,5,6] ``` ``` [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] ``` ``` [] ``` ``` [1] ``` -->