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 {
    
    };
        }

        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;
    }
};

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

/*
// 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