二叉树及其遍历
来源:互联网 发布:矩阵的合同矩阵怎么求 编辑:程序博客网 时间: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就是一搜到底对树来说有前序,中序,后序遍历。。。
- 二叉树及其遍历
- 二叉树及其遍历
- 二叉树及其遍历
- 二叉树及其遍历
- 排序二叉树及其遍历
- 遍历二叉树及其应用
- 二叉树创建及其遍历
- 二叉树及其遍历算法
- 普通二叉树及其遍历
- 二叉树及其各种遍历
- 线索二叉树及其遍历
- 遍历二叉树及其应用
- 二叉树及其应用--二叉树遍历
- 二叉树及其遍历方式(java)
- 二叉树建立及其遍历模板
- 二叉树的存储结构及其遍历
- 数据结构之二叉树创建及其遍历
- 二叉树的遍历及其Java实现
- ios学习--iOS CVImageBuffer distorted from AVCaptureSessionDataOutput with AVCaptureSessionPresetPhoto
- C语言中的零值比较
- 王利芬反思创业失误
- 在androidMainfest.xml文件中在此Activity中写入 android:windowSoftInputMode="adjustPan" 可以让界面不被弹出的键盘挤上去。
- ubuntu 更新问题!(纠结的,搞了好几天!呵呵!总算搞定了!)
- 二叉树及其遍历
- 关于contextMenuStrip控件的定位问题
- Android面试之----谈谈你对Java中Native关键字的认识!
- Android面试之----Android系统架构图及简单的系统架构介绍
- 你最近学到的 飞鸽传书 东西的题目
- 优米网王利芬:一个人能否成才取决于四点
- Android面试之---谈谈你对Android NDK的理解.
- 多重循环下的continue的使用
- exit()与_exit()的区别