Given an n-ary tree, return the preorder traversal of its nodes' values.html
For example, given a 3-ary
tree:node
Return its preorder traversal as: [1,3,5,6,2,4]
.數組
Note:函數
Recursive solution is trivial, could you do it iteratively?post
這道題讓咱們求N叉樹的前序遍歷,有以前那道Binary Tree Preorder Traversal的基礎,知道了二叉樹的前序遍歷的方法,很容易就能夠寫出N叉樹的前序遍歷。先來看遞歸的解法,主要實現一個遞歸函數便可,判空以後,將當前結點值加入結果res中,而後遍歷子結點數組中全部的結點,對每一個結點都調用遞歸函數便可,參見代碼以下:url
解法一:spa
class Solution { public: vector<int> preorder(Node* root) { vector<int> res; helper(root, res); return res; } void helper(Node* node, vector<int>& res) { if (!node) return; res.push_back(node->val); for (Node* child : node->children) { helper(child, res); } } };
咱們也能夠使用迭代的解法來作,使用棧stack來輔助,須要注意的是,若是使用棧的話,咱們遍歷子結點數組的順序應該是從後往前的,由於棧是後進先出的順序,因此須要最早遍歷的子結點應該最後進棧,參見代碼以下:code
解法二:htm
class Solution { public: vector<int> preorder(Node* root) { if (!root) return {}; vector<int> res; stack<Node*> st{{root}}; while (!st.empty()) { Node* t = st.top(); st.pop(); res.push_back(t->val); for (int i = (int)t->children.size() - 1; i >= 0; --i) { st.push(t->children[i]); } } return res; } };
相似題目:blog
Binary Tree Preorder Traversal
N-ary Tree Level Order Traversal
N-ary Tree Postorder Traversal
參考資料:
https://leetcode.com/problems/n-ary-tree-preorder-traversal/