leetcode 590. N叉树的后序遍历(N-ary Tree Postorder Traversal)

题目描述:

给定一个 N 叉树,返回其节点值的后序遍历

例如,给定一个 3叉树 :

返回其后序遍历: [5,6,3,2,4,1].

说明: 递归法很简单,你可以使用迭代法完成此题吗?


解法:

/*
// 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> res;
        if(root){
            for(Node* child : root->children){
                vector<int> lst = postorder(child);
                res.insert(res.end(), lst.begin(), lst.end());
            }
            res.push_back(root->val);
        }
        return res;
    }
};
posted @ 2019-03-26 15:12  zhanzq1  阅读(103)  评论(0)    收藏  举报