题目描述:
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]
.
解题思路:
递归方法后序排序。
代码:
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 vector<Node*> children; 7 8 Node() {} 9 10 Node(int _val, vector<Node*> _children) { 11 val = _val; 12 children = _children; 13 } 14 }; 15 */ 16 class Solution { 17 public: 18 vector<int> postorder(Node* root) { 19 vector<int> ret; 20 ret.reserve(1000); 21 post(root, ret); 22 return ret; 23 } 24 void post(Node* root, vector<int>& ret) { 25 if (root == NULL) 26 return; 27 for (auto node : root->children) { 28 post(node, ret); 29 } 30 ret.push_back(root->val); 31 } 32 };