打卡
给出一棵二叉树,返回其节点值的后序遍历。
主函数(左右中)
class Solution {
public:
vector<int> ans;
void dfs(TreeNode *root){
if(root==NULL) return;
dfs(root->left);
dfs(root->right);
ans.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode *root) {
dfs(root);
return ans;
}
};
构造节点模板
class TreeNode {
public:
int val;
TreeNode *left, *right;
TreeNode(int val) {
this->val = val;
this->left = this->right = NULL;
}
}