Given an n-ary tree, return the postorder traversal of its nodes' values.html
For example, given a 3-ary
tree:node
Return its postorder traversal as: [5,6,3,2,4,1]
.數組
Note:函數
Recursive solution is trivial, could you do it iteratively?post
這道題讓咱們求N叉樹的後序遍歷,因爲有了以前那道 Binary Tree Postorder Traversal 的基礎,瞭解了二叉樹的後序遍歷,則N叉樹的後序遍歷也就沒有那麼難了。首先仍是用遞歸來作,在遞歸函數中,判空後,遍歷子結點數組,對全部的子結點調用遞歸函數,而後在 for 循環以外在將當前結點值加入結果 res 數組,這樣才能保證是後序遍歷的順序,參見代碼以下:url
解法一:spa
class Solution { public: vector<int> postorder(Node* root) { vector<int> res; helper(root, res); return res; } void helper(Node* node, vector<int>& res) { if (!node) return; for (Node* child : node->children) { helper(child, res); } res.push_back(node->val); } };
咱們也能夠使用迭代的方法來作,這裏有個小 trick,寫法跟先序遍歷十分的像,不一樣的就是每次把從 stack 中取的結點的值都加到結果 res 的最前面,還有就是遍歷子結點數組的順序是正常的順序,而前序遍歷是從子結點數組的後面往前面遍歷,這點區別必定要注意,參見代碼以下:code
解法二:htm
class Solution { public: vector<int> postorder(Node* root) { if (!root) return {}; vector<int> res; stack<Node*> st{{root}}; while (!st.empty()) { Node *t = st.top(); st.pop(); res.insert(res.begin(), t->val); for (Node* child : t->children) { if (child) st.push(child); } } return res; } };
相似題目:blog
Binary Tree Postorder Traversal
N-ary Tree Level Order Traversal
參考資料:
https://leetcode.com/problems/n-ary-tree-preorder-traversal/