N叉树的后序遍历

264 阅读1分钟

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

递归

class Solution{

public:

vector<int>postorder(Node*root){

vector<int>temp;

if(!root)return temp;

for(auto i:root->children){

postorder(i);

}

res.push_back(root->val);

return res;

}

};

迭代

class Solution{
public:

vector<int>postorder(Node*root){
vector<int>res;

if(!root)

return res;

stack<Node*>stk;

stk.push(root);

while(!stk.empty()){

Node*temp=stk.top();

stk.pop();

res.push_back(temp->val);

for(auto i :temp->children){

stk.push(i);

}

}

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

return res;

}

}