题目描述

给定一个 N 叉树,返回其节点值的后序遍历。

例如,给定一个 3叉树

返回其后序遍历: [5,6,3,2,4,1].

代码

class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> res;//存储后序遍历的结果
        stack<Node *> s; //栈里面存放的是节点

        if(!root)
            return res;
        s.push(root);//根节点入栈
        while(!s.empty()) //栈不为空时
        {
            Node *p = s.top();
            s.pop();
            res.push_back(p->val);
            for(int i = 0; i < p->children.size(); i++)
                s.push(p->children[i]);

        }
        reverse(res.begin(),res.end());
        return res;
    }
};