776. N-ary Tree Postorder Traversal

Problem:

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?

Solutions:

/*
// 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> ret;
        helper(root, ret);
        return ret;
    }

private:
    void helper(Node* root, vector<int>& ret) {
        if (root == nullptr)    return;
        for (auto& child : root->children) {
            helper(child, ret);
        }
        ret.push_back(root->val);
    }

};

results matching ""

    No results matching ""