LeetCode——N-ary Tree Postorder Traversal(590)

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].

分析:

典型的树遍历

代码:

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

static const auto __ = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();
class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> ress;
        stack<Node*> res;
        if(!root)
            return ress;
        Node* temp;
        res.push(root);
        while(!res.empty())
        {
            temp = res.top();
            res.pop();
            for(int i=0;i<temp->children.size();++i)
                res.push(temp->children[i]);
            ress.push_back(temp->val);
        }
        reverse(ress.begin(), ress.end());
        return ress;
    }
};

猜你喜欢

转载自blog.csdn.net/Pokemon_Master/article/details/82819807