C++Leetcode590:N叉树的后序遍历

题目
给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树 :
C++Leetcode590:N叉树的后序遍历
返回其后序遍历: [5,6,3,2,4,1].

思路
1、递归。
2、迭代。我的方法可能稍微有些复杂,额外用了一个set,存储遍历过的根结点,以防止重复遍历,进入死循环。

实现方法
一、递归

/*
// 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;
        postorder(root,res);
        return res;
    }
    
    void postorder(Node* root, vector<int> &res){
        if(root){
            for(int i=0;i<root->children.size();i++)
                postorder(root->children[i],res);
            res.push_back(root->val);
        }
    }
};

二、迭代

/*
// 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) return res;
        stack<Node*> s;
        unordered_set<Node*> ss;
        s.push(root);
        while(!s.empty()){
            Node* tmp=s.top();
            if(tmp->children.size()!=0){
                if(ss.count(tmp)>=1){
                    res.push_back(tmp->val);
                    s.pop();
                    continue;
                }else{
                    for(int i=tmp->children.size()-1;i>=0;i--)
                        s.push(tmp->children[i]);
                }
                ss.insert(tmp);
            }else{
                res.push_back(tmp->val);
                s.pop();
            } 
        }
        return res;
    }
};