[LeetCode] N-ary Tree Preorder Traversal N叉樹的前序遍歷
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?
這道題讓我們求N叉樹的前序遍歷,有之前那道Binary Tree Preorder Traversal的基礎,知道了二叉樹的前序遍歷的方法,很容易就可以寫出N叉樹的前序遍歷。先來看遞歸的解法,主要實現一個遞歸函數即可,判空之後,將當前結點值加入結果res中,然後遍歷子結點數組中所有的結點,對每個結點都調用遞歸函數即可,參見代碼如下:
解法一:
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來輔助,需要註意的是,如果使用棧的話,我們遍歷子結點數組的順序應該是從後往前的,因為棧是後進先出的順序,所以需要最先遍歷的子結點應該最後進棧,參見代碼如下:
解法二:
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; } };
類似題目:
Binary Tree Preorder Traversal
N-ary Tree Level Order Traversal
N-ary Tree Postorder Traversal
參考資料:
https://leetcode.com/problems/n-ary-tree-preorder-traversal/
https://leetcode.com/problems/n-ary-tree-preorder-traversal/discuss/147955/Java-Iterative-and-Recursive-Solutions
LeetCode All in One 題目講解匯總(持續更新中...)
[LeetCode] N-ary Tree Preorder Traversal N叉樹的前序遍歷