N-ary Tree Postorder Traversal

迭代

/*
// 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);
    }
};

 

上一篇:JAVA小练习129——自定义一个性别类, 限制着别人任意创建该类的对象(枚举)


下一篇:python – 金字塔遍历正在努力