N-ary Tree Postorder Traversal

Posted liuqiujie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
};

 

以上是关于N-ary Tree Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

N-ary Tree Postorder Traversal

(N叉树 递归) leetcode 590. N-ary Tree Postorder Traversal

[LeetCode] 590. N-ary Tree Postorder Traversal_Easy

[LeetCode&Python] Problem 590. N-ary Tree Postorder Traversal

Leetcode 590. N-ary Tree Postorder Traversal

Leetcode590. N-ary Tree Postorder Traversal