(N叉树 递归) leetcode 590. N-ary Tree Postorder Traversal

mac2022-06-30  114

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?

---------------------------------------------------------------------------------------------------------------------------------

和leetcode589. N-ary Tree Preorder Traversal类似。用递归会简单些

C++代码:

/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: vector<int> postorder(Node* root) { vector<int> vec; helper(root,vec); return vec; } void helper(Node* root,vector<int> &vec){ if(!root) return; for(Node *cur:root->children){ helper(cur,vec); } vec.push_back(root->val); } };

 

转载于:https://www.cnblogs.com/Weixu-Liu/p/10776100.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)