LeetCode 590. N 叉树的后序遍历

给定一个 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) {
        if (root == nullptr) {
            return {};
        }

        vector<int> res;
        for (Node *curNode : root->children) {
            vector<int> fromChild = postorder(curNode);
            res.insert(res.end(), fromChild.begin(), fromChild.end());
        }
        res.push_back(root->val);

        return res;
    }
};

法二:循环法:使用栈遍历整个树,每当遍历到一个节点,将该节点存入结果数组和栈,之后将其子节点从左到右压栈,重复此过程,最后将结果数组反过来即可:

/*
// 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;
    }
};
posted @ 2021-03-25 23:19  epiphanyy  阅读(11)  评论(0)    收藏  举报  来源