统计利用先序遍历创建的二叉树的宽度
2016-04-14 16:12
351 查看
方案一:递归实现
通过设置一个计数数组,记录每一层的结点数
方案二:
层次遍历,队列实现
通过设置一个计数数组,记录每一层的结点数
#include <iostream> #include <stdlib.h> using namespace std; typedef struct BiNode { char data; BiNode *lchild,*rchild; }BiNode,*BiTree; int count[1000]={0},Max=0;//count记录每层的节点数,Max记录宽度 BiTree CreatBiTree()//先序遍历创建二叉树 { BiTree T; char ch; cin>>ch; if(ch=='#') T=NULL; else { T=(BiTree)malloc(sizeof(BiNode)); T->data=ch; T->lchild=CreatBiTree(); T->rchild=CreatBiTree(); } return T; } void getnum(BiTree T,int i) { if(T!=NULL) { count[i]++;//第i层结点数+1 if(count[i]>Max)Max=count[i]; getnum(T->lchild,i+1);//T的左孩子,层数+1 getnum(T->rchild,i+1);//T的右孩子,层数+1 } } int main() { BiTree T; T=CreatBiTree(); getnum(T,1); cout<<Max; return 0; }
方案二:
层次遍历,队列实现
#include <iostream> #include <algorithm> #include <queue> #include <stdlib.h> using namespace std; typedef struct node { char dada; node *lchild,*rchild; }BiNode,*BiTree; BiTree CreatBiTree() { char ch;BiTree T; cin>>ch; if(ch=='#') T=NULL; else { T=(BiTree)malloc(sizeof(BiNode)); T->dada=ch; T->lchild=CreatBiTree(); T->rchild=CreatBiTree(); } return T; } int Max=0; void GetNum(BiTree T) { if(T!=NULL) { queue<BiTree>q; q.push(T); while(1) { int len=q.size();//当前遍历层的宽度 if(len>Max)Max=len;//Max记录最大宽度(树的宽度) if(len==0) break; while(len--)//当前层遍历结束后,队列的长度为下一层的宽度 { BiTree now; now=q.front(); q.pop(); if(now->lchild!=NULL) q.push(now->lchild); if(now->rchild!=NULL) q.push(now->rchild); } } } } int main() { BiTree T=CreatBiTree(); GetNum(T); cout<<Max; return 0; }
相关文章推荐
- 数据库学习整理
- 码农小汪-设计模式之-Builder模式
- ios 内置支付宝
- inline函数详解
- 对于数据库操作可能会遇到的问题(空值问题以及出现的参数不能被重复使用问题)
- oc知道经纬度求位置
- 浅谈算法和数据结构: 七 二叉查找树
- 微软官方补丁6B BUG造成WIN7系统蓝屏解决方案
- 8.2检测图像中的角点
- 微信支付异步回调的坑,调用成功了回调地址却没有数据
- LeetCode 142 Linked List Cycle II
- 队列——链表实现
- Linux服务器集群负载均衡解说
- ansible学习笔记
- 万能的NSData各种数据类型之间的转化
- Quartz的简单使用
- PL SQL 修改 日期 显示格式
- Learning Scrapy笔记(一)- Scrapy简单介绍
- mysql 5.7.7+支持JSON字段格式
- bzoj3339 Rmq Problem