都是递归;没得说,搞清楚前、中、后序的定义就懂了,为了更贴合,和更好解释,我这儿用c++写,改成c python都差不多,python太简洁反而不美。
class Solution {
public:
vectorans;
vector preorderTraversal(TreeNode* root) {
help(root);
return ans;
}
void help(TreeNode* root){
if (root==nullptr){
return;
}
ans.push_back(root->val);
help(root->left);
help(root->right);
}
};
94. 二叉树的中序遍历
class Solution {
public:
vector ans;
vector inorderTraversal(TreeNode* root) {
help(root);
return ans;
}
void help(TreeNode* root){
if (root==nullptr){
return;
}
help(root->left);
ans.push_back(root->val);
help(root->right);
}
};
145. 二叉树的后序遍历
class Solution {
public:
vector ans;
vector postorderTraversal(TreeNode* root) {
help(root);
return ans;
}
void help(TreeNode* root){
if (root==nullptr){
return;
}
help(root->left);
help(root->right);
ans.push_back(root->val);
}
};



