一、基本操作
1、查找
2、插入
3、建立
4、删除
二、问题
7 8 6 5 7 10 8 11 7 8 10 11 8 6 7 5 7 8 6 8 5 10 9 11
测试代码:
//0 cout<<"origin:"; for(int i=0;i<(int)origin.size();i++){ cout<<origin[i]<<" "; } cout<<endl; //1 cout<<"pre:"; for(int i=0;i<(int)pre.size();i++){ cout<<pre[i]<<" "; } cout<<endl; //2 cout<<"prem:"; for(int i=0;i<(int)prem.size();i++){ cout<<prem[i]<<" "; } cout<<endl; //3 cout<<"post:"; for(int i=0;i<(int)post.size();i++){ cout<<post[i]<<" "; } cout<<endl; //4 cout<<"postm:"; for(int i=0;i<(int)postm.size();i++){ cout<<postm[i]<<" "; } cout<<endl;
代码:
#include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <vector> using namespace std; struct node{ int data; node *left,*right; }; void insert(node* &root,int data); void preorder(node* root,vector<int>&vi); void preorderm(node* root,vector<int>&vi); void postorder(node* root,vector<int>&vi); void postorderm(node* root,vector<int>&vi); int main(){ int n,dt; while(cin>>n){ node *root = NULL; vector<int> origin,pre,post,prem,postm; for(int i=0;i<n;i++){ cin>>dt; origin.push_back(dt); insert(root,dt); } preorder(root,pre); preorderm(root,prem); postorder(root,post); postorderm(root,postm); if(origin==pre){ cout<<"YES"<<endl; for(int i=0;i<(int)post.size();i++){ cout<<post[i]<<" "; } cout<<endl; }else if(origin==prem){ cout<<"YES"<<endl; for(int i=0;i<(int)postm.size();i++){ cout<<postm[i]<<" "; } cout<<endl; }else{ cout<<"NO"<<endl; } } return 0; } void insert(node* &root,int data){ if(root==NULL){ root = new node; root->data = data; root->left=root->right=NULL; return; } if(data<root->data){ insert(root->left,data); }else{ insert(root->right,data); } } void preorder(node* root,vector<int>&vi){//先序遍历,结果存在vi if(root==NULL){ return; } vi.push_back(root->data); preorder(root->left,vi); preorder(root->right,vi); } void preorderm(node* root,vector<int>&vi){//镜像先序遍历,结果存在vi if(root==NULL){ return; } vi.push_back(root->data); preorderm(root->right,vi); preorderm(root->left,vi); } void postorder(node* root,vector<int>&vi){//后序遍历,结果存在vi if(root==NULL){ return; } postorder(root->left,vi); postorder(root->right,vi); vi.push_back(root->data); } void postorderm(node* root,vector<int>&vi){//镜像后序遍历,结果存在vi if(root==NULL){ return; } postorderm(root->right,vi); postorderm(root->left,vi); vi.push_back(root->data); }