二叉树的建立和遍历
来源:互联网 发布:记分牌算法 编辑:程序博客网 时间:2024/06/03 19:36
首先,有一颗二叉树,形如:
有了要建立的二叉树,就好办了。只要在输入数据时输入DBA##C##EF##G##即可。
先用一个结构体来定义二叉树
typedef struct node{ struct node *lc; //左孩子 struct node *rc; //右孩子 char data;}NODE;
之后,在写一个函数,递归建立二叉树,在主函数中调用即可。
NODE *buildTrea(){ char a; cin>>a; if(a=='#') return NULL; NODE *t = new node; t->date = a; t->lc = buildTree(); t->rc = buildTree(); return t;}
二叉树建好之后,就可以进行遍历了,遍历二叉树有,前序遍历,中序遍历,后序遍历。这三种遍历方式,代码都不长,是有规律的。
//前序遍历void preorder(NODE *t){ if(t!=NULL){ cout<<t-data; preorder(t->lc); preorder(t->rc); }}
//中序遍历void inorder(NODE *t){ if(t!=NULL){ inorder(t->lc); cout<<t->data; inorder(t->rc); }}
//后序遍历void postorder(NODE *t){ if(t!=NULL){ postorder(t->lc); postorder(t->rc); cout<<t->data; }}
其实,观察以上三段代码,不难发现规律,就是输出语句放在,if语句中的,前中后的那个位置之中,就是那种方式进行遍历二叉树。
出以上三种方式遍历二叉树以外,还有镜像遍历,层次遍历。
镜像遍历和中序遍历,很像。层次遍历,就是互换左右孩子,
//镜像遍历void mirror(NODE *t){ if(t!=NULL){ mirror(t->rc); cout<<t->data; mirror(t->lc); }}
层次遍历,顾名思义,就是一层一层的遍历。如图:
//层次遍历,这里使用队列(queue)//先进先出void level(NODE *t){ queue<NODE*>q; NODE *root = t; while(t==NULL) return; q.push(t); //放入队列 while(!q.empty()){ root = q.front(); //获取最前的一个 cout<<root->data; q.pop(); //弹出 if(root->lc!=NULL) q.push(root->lc); if(root->rc!=NULL) q.push(root->rc); }}
完整代码:
#include<iostream>#include<algorithm>#include<queue>using namespace std;typedef struct node{ char date; struct node *lc; struct node *rc;}NODE;NODE* buildTree(){ char a; cin>>a; if(a=='#')return NULL; NODE *p = new node; p->date = a; p->lc = buildtree(); p->rc = buildtree(); return p; }//前序遍历 void preorder(NODE *t){ if(t!=NULL){ cout<<t->date; preorder(t->lc); preorder(t->rc); } }//中序遍历void inorder(NODE *t){ if(t!=NULL){ inorder(t->lc); cout<<t->date; inorder(t->rc); } } //后序遍历 void postorder(NODE *t){ if(t!=NULL){ postorder(t->lc); postorder(t->rc); cout<<t->date; }}//镜像遍历 void mirror(NODE *t){ if(t!=NULL){ mirror(t->rc); cout<<t->date; mirror(t->lc); }}//层次遍历 void level(NODE *t){ queue<NODE*>q; NODE *root = t; while(t==NULL) return; q.push(t); while(!q.empty()){ root = q.front(); cout<<root->date; q.pop(); if(root->lc!=NULL) q.push(root->lc); if(root->rc!=NULL) q.push(root->rc);; }}int main(){ NODE *root = NULL; root = buildtree(); preorder(root); cout<<endl; inorder(root); cout<<endl; postorder(root); cout<<endl; mirror(root); cout<<endl; level(root);}
PS:之前在做测试的时候,用过数字进行测试,421003005600700,但是,输出的结果总是2147483647,纳闷好久,现在我也搞不懂,自己真的是太菜了。换了DBA##C##EF##G##,这组数据,结果和自己想得一样。
阅读全文
0 0
- 二叉树的建立和遍历
- 二叉树 普通的 建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- Tree 二叉树的建立 和遍历
- 二叉树的建立和遍历
- [转]二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历算法
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 线索二叉树的建立和遍历
- HDU1257 最少拦截系统 DP(最大递增子序列)
- csv 按指定列顺序写入
- MicroSoft:面试题收集与解题思路
- Broadcast和BroadcastReciver的安全使用
- 给初学PLC编程的朋友几点建议
- 二叉树的建立和遍历
- IMEI、MEID、ICCID、UDID、IMSI
- spark,hadoop,hbase集群无法停止的问题
- C#网页分页标签生成
- RedLock
- 程序员:天天加班,但是加班费呢?
- 剑指offer题解C++【25】复杂链表的复制
- 设置cell分割线的高度
- 在Ubuntu 12.10下安装 jdk-7u10-linux-x64.tar.gz