二叉树及其遍历

来源:互联网 发布:矩阵的合同矩阵怎么求 编辑:程序博客网 时间:2024/05/21 19:09

好吧,我承认关于深度优先搜索和宽度优先搜索以前我确实没有理解,,,,抓狂

#include<iostream>#include<string.h>#include<string>#define N 1000#include<queue>using namespace std;int ans[N];int tot;typedef struct Tnode{int flag;int v;struct Tnode *left,*right;}*Node,T;char s[N+100];bool failed;Node root;Node newnode(){Node u=new T;if(u!=NULL){u->flag=0;u->left=u->right=NULL;}return u;}void addnode(int v,char* s){int n=strlen(s);Node u=root;for(int i=0;i<n;++i)  if(s[i]=='L'){  if(u->left==NULL) u->left=newnode();    u=u->left;}else if(s[i]=='R'){if(u->right==NULL) u->right=newnode();u=u->right;}  if(u->flag) failed=1;//输入错误就是一个结点输入两次时  u->v=v;  u->flag=1;}void delet(Node root){if(root->left) delet(root->left);if(root->right) delet(root->right);delete root;}void pre_order(Node root){cout<<root->v<<" ";if(root->left) pre_order(root->left);if(root->right) pre_order(root->right);}void mid_order(Node root){if(root->left) mid_order(root->left);cout<<root->v<<" ";if(root->right) mid_order(root->right);}void post_order(Node root){if(root->left) post_order(root->left);if(root->right) post_order(root->right);cout<<root->v<<" ";}bool bfs()//一层一层的搜索。。。{   tot=0;int rear=1,front=0;//模拟队列Node q[N];q[0]=root;while(front<rear){Node u=q[front++];if(!u->flag) return false;ans[tot++]=u->v;if(u->left) q[rear++]=(u->left);if(u->right)q[rear++]=(u->right);}return true;}int main(){int T;cin>>T;while(T--){  memset(ans,0,sizeof(ans));failed=0;  root=newnode(); getchar();while(scanf("%s",s)&&strcmp(s,"()")){int v;sscanf(&s[1],"%d",&v);addnode(v,strchr(s,',')+1);//返回s字符串中第一个出现,的位置}if(!bfs()||failed) {cout<<"-1"<<endl;continue;}else {cout<<"宽度优先搜索:"<<endl;  for(int i=0;i<tot;++i)cout<<ans[i]<<" ";     cout<<endl;     }cout<<"深度优先搜索: "<<endl;cout<<"前序遍历:"<<endl;pre_order(root);cout<<endl;cout<<"中序遍历:"<<endl;mid_order(root);cout<<endl;cout<<"后序遍历:"<<endl;post_order(root);cout<<endl;delet(root);}return 0;}
就树来说吧,所谓的bfs就是对树一层一层的遍历。。。所谓的dfs就是一搜到底对树来说有前序,中序,后序遍历。。。



原创粉丝点击