RT,在网上背了二叉树前、中、后序遍历的模板,但是中、后序似乎连我自己造的样例数据都过不去,但是没看出问题(我太弱了),求条。
#include<cstdio>
#include<vector>
#define null nullptr
using namespace std;
struct Node{
int val;
Node *left;
Node *right;
Node(): val(0),left(null),right(null) {}
Node(int x): val(x),left(null),right(null) {}
Node(int x,Node *l,Node *r): val(x),left(l),right(r) {}
};
void pre(Node *root,vector<int> &res){
if(root==null) return;
res.push_back(root->val);
pre(root->left,res);
pre(root->right,res);
}
void mid(Node *root,vector<int> &res){
if(root==null) return;
pre(root->left,res);
res.push_back(root->val);
pre(root->right,res);
}
void lst(Node *root,vector<int> &res){
if(root==null) return;
pre(root->left,res);
pre(root->right,res);
res.push_back(root->val);
}
vector<int> build1(Node *root){
vector<int> res;
pre(root,res);
return res;
}
vector<int> build2(Node *root){
vector<int> res;
mid(root,res);
return res;
}
vector<int> build3(Node *root){
vector<int> res;
lst(root,res);
return res;
}
int main(){
// 以下是自己造的数据
Node *A=new Node(1);
Node *B=new Node(2);
Node *C=new Node(3);
Node *D=new Node(4);
Node *E=new Node(5);
Node *F=new Node(6);
A->left=B;
A->right=C;
B->left=D;
B->right=E;
D->right=F;
//
vector<int> ans1=build1(A);
vector<int> ans2=build2(A);
vector<int> ans3=build3(A);
for(auto x:ans1) printf("%d ",x);
printf("\n");
for(auto x:ans2) printf("%d ",x);
printf("\n");
for(auto x:ans3) printf("%d ",x);
printf("\n");
return 0;
}