LeetCode 590.N-aryツリーのポストオーダートラバーサル

N-aryツリーが与えられた場合、そのノード値のポストオーダートラバーサルを返します。

方法1:直接解決する再帰的方法:

/*
// 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) {
    
    
        if (root == nullptr) {
    
    
            return {
    
    };
        }

        size_t sz = root->children.size();

        vector<int> res;
        for (size_t i = 0; i < sz; ++i) {
    
    
            vector<int> fromChild = postorder(root->children[i]);
            res.insert(res.end(), fromChild.begin(), fromChild.end());
        }
        res.push_back(root->val);

        return res;
    }
};

方法2:再帰的方法:スタックを使用してツリー全体をトラバースします。ノードがトラバースされるたびに、ノードを結果配列に格納し、その子ノードを左から右にスタックにプッシュし、このプロセスを繰り返し、最後に結果配列。できます:

/*
// 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) {
    
    
        if (root == nullptr) {
    
    
            return {
    
    };
        }

        vector<int> ret;
        stack<Node *> stk;
        stk.push(root);
        Node *cur = stk.top();
        while (!stk.empty()) {
    
    
            cur = stk.top();
            ret.push_back(cur->val);
            stk.pop();
            for (Node *n : cur->children) {
    
    
                stk.push(n);
            }
        }
        reverse(ret.begin(), ret.end());

        return ret;
    }
};

おすすめ

転載: blog.csdn.net/tus00000/article/details/115191542