参考文献
先序遍历是DLR,所以数组ans最先把root的值放进去,后遍历其子结点。
后序遍历是LRD,所以数组ans最后把root的值放进去,先遍历其子结点。
C++ 589代码
class Solution {
public:
vector<int> ans;
vector<int> postorder(Node* root) {
if(!root) return ans;
dfs(root);
return ans;
}
void dfs(Node* root)
{
if(!root) return ;
ans.push_back(root->val); //最先放进去
for(auto x:root->children)
dfs(x);
}
};
C++ 590代码
class Solution {
public:
vector<int> ans;
vector<int> postorder(Node* root) {
if(!root) return ans;
dfs(root);
return ans;
}
void dfs(Node* root)
{
if(!root) return ;
for(auto x:root->children)
dfs(x);
ans.push_back(root->val); //最后放进去
}
};