590. N-ary Tree Postorder Traversal

题目描述:

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 };

 

转载于:https://www.cnblogs.com/gsz-/p/9500351.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值