###### tags: `LeetCode` `Recursion` `Tree` `Preorder` `Medium` `Easy` `Iterative` `Stack` # LeetCode #589 [N-ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal/) ### (Easy):Recursion (Medium):Iterative 給定一個 N 元樹,返回其節點值的前序遍歷 。 N 元樹 在輸入中按層序遍歷進行序列化表示,每組子節點由空值 null 分隔。 --- 遞迴法 : 與#144類似, 只是子節點變多, 將原本傳入左右子節點改為傳入全部子節點(已排序)即可。 ``` class Solution { public: vector<int> preorder(Node* root) { if(root==nullptr)return {}; vector<int> nodes; helper(root, nodes); return nodes; } void helper(Node* root, vector<int>& nodes){ if(root){ nodes.push_back(root->val); for(Node* child:root->children){ helper(child, nodes); } } } }; ``` --- 迭代法 : 利用堆疊特性, 堆疊的放入順序與印出順序相反, 所以每次將父節點的值插入答案數組中, 並將子節點由右往左放入堆疊。 ``` class Solution { public: vector<int> preorder(Node* root) { if(root==nullptr)return {}; vector<int> nodes; stack<Node*> s; s.push(root); while(!s.empty()){ Node* cur=s.top();s.pop(); nodes.push_back(cur->val); for(int i=cur->children.size()-1;i>=0;i--){ s.push(cur->children[i]); } } return nodes; } }; ```