Easy Given an n-ary tree, return the postorder traversal of its nodes‘ values. For example, given a 3-ary tree: Return its postorder traversal as: [5,6,3,2,4,1] . Note: Recursive solution is trivial, could you do it iteratively? 题目大意
Easy
Given an n-ary tree, return the postorder traversal of its nodes‘ values.
For example, given a 3-ary
tree:
Return its postorder traversal as: [5,6,3,2,4,1]
.
Note:
Recursive solution is trivial, could you do it iteratively?
题目大意:对n-ary树后序遍历。尝试递归和迭代两种方法。
后序遍历是左->右->根
方法一:递归
将子树当做一个节点,对子树递归调用函数的结果作为根节点的子节点,并按序合并入结果数组中。
代码如下:
class Solution { public: vector<int> postorder(Node* root) { if(!root)return {}; vector<int> res; if(!root->children.empty()){ vector<Node*>temp=root->children; for(int i=0;i<temp.size();++i){ vector<int> t=postorder(temp[i]); res.insert(res.end(),t.begin(),t.end()); } } res.push_back(root->val); return res; } };
方法二:迭代
将数据按照遍历的逆顺序放入堆栈中,然后再依次取出遍历那个节点的孩子节点,直到全部节点遍历。
代码如下:
class Solution { public: vector<int> postorder(Node* root) { if(!root)return {}; vector<int> res; stack<Node*> s{{root}}; while(!s.empty()){ Node* temp = s.top(); s.pop(); res.insert(res.begin(),temp->val); if(!temp->children.empty()){ vector<Node*> t=temp->children; for(int i=0;i<t.size();++i){ s.push(t[i]); } } } return res; } };