树的建立和遍历
来源:互联网 发布:linux java home 配置 编辑:程序博客网 时间:2024/06/05 19:29
这段代码实现了二叉树的建立和前序、中序、后序、层序四种输出顺序
#include<stdio.h>#include<stdlib.h> #include<iostream>#include<queue>using namespace std;struct tree{int data;struct tree *l,*r;};void creatTree(int a,struct tree * &t);void preorder(struct tree *t);void inorder(struct tree *t);void postorder(struct tree *t);void layerorder(struct tree *t);int main(){int n,order;struct tree *root;root=NULL;printf("the amount of node:\n");scanf("%d",&n);printf("data:\n");for(int i=0;i<n;i++){int num;scanf("%d",&num);creatTree(num,root);}while(1){printf("which order do you want to choose\n");printf("1.preorder 2.inorder 3.postorder 4.layerorder 5.exit\n");scanf("%d",&order);switch(order){case 1:{preorder(root);putchar('\n');break;}case 2:{inorder(root);putchar('\n');break;}case 3:{postorder(root);putchar('\n');break;}case 4:{layerorder(root);putchar('\n');break;}case 5:exit(0);}}return 0;}void creatTree(int a,struct tree * &t){if(t==NULL){struct tree *Node=new struct tree;Node->data=a;Node->l=NULL;Node->r=NULL;t=Node;return ;}if(a<t->data){creatTree(a,t->l);}else if(a==t->data){return ;}else if(a>t->data){creatTree(a,t->r);}}void preorder(struct tree *t){if(t==NULL)return ;printf("%d ",t->data);preorder(t->l);preorder(t->r);}void inorder(struct tree *t){if(t==NULL)return ;inorder(t->l);printf("%d ",t->data);inorder(t->r);}void postorder(struct tree *t){if(t==NULL)return ;postorder(t->l);postorder(t->r);printf("%d ",t->data);}void layerorder(struct tree *t){queue<struct tree*> q;q.push(t);while(!q.empty()){printf("%d ",q.front()->data);if(q.front()->l!=NULL)q.push(q.front()->l);if(q.front()->r!=NULL)q.push(q.front()->r);q.pop();}}
阅读全文
0 0
- 树的建立和遍历
- 树的建立和遍历
- 二叉树的建立和遍历
- 二叉树 普通的 建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- Tree 二叉树的建立 和遍历
- 二叉树的建立和遍历
- [转]二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历算法
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 根据下拉展示不同的表格内容
- IEEE Spectrum 2017 编程语言排行:Python 夺冠
- shiro内置过滤器研究
- Springboot+Thymeleaf配置与使用
- 微信小程序开发笔记
- 树的建立和遍历
- ubuntu 安装ImageMagic
- Python实现——CAN报文转换工具
- php使用pdo数据库连接失败
- Cinder学习--关于存储的相关概念
- 固定在顶部的进度条
- 2017 Multi-University Training Contest
- 链接数据库的—MyBatis—事务
- 关于在Eclipse中使用函数名查找定义此函数的js文件