N-ary Tree Postorder Traversal N叉树的后序遍历

迭代

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> vec;
        stack<Node*> s;
        unordered_map<Node*,bool> m;
        Node* node=root;
        while(node||!s.empty()) {
            while(node) {
                s.push(node);
                m[node]=true;
                bool flag=false;
                for(auto& child:node->children) {
                    if(!m.count(child)) {node=child;flag=true;break;}
                }
                if(!flag) node=nullptr;
            }
            if(!s.empty()) {
                node=s.top();
                bool flag=false;
                for(auto& child:node->children) {
                    if(!m.count(child)) {node=child;flag=true;break;}
                }
                if(!flag) {
                    node=nullptr;
                    vec.push_back(s.top()->val);
                    s.pop();
                }
            }
        }
        return vec;
    }
};

 递归

class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> vec;
        postorder_helper(root,vec);
        return vec;
    }
    void postorder_helper(Node* node,vector<int>& vec) {
        if(!node) return;
        for(auto& child:node->children) {
            postorder_helper(child,vec);
        }
        vec.push_back(node->val);
    }
};

 

posted @ 2020-03-16 11:58  qiujiejie  阅读(89)  评论(0编辑  收藏  举报