求二叉树的高度以及二叉树的树形显示
来源:互联网 发布:子域名和二级域名 编辑:程序博客网 时间:2024/05/20 02:56
二叉树的高度用递归的方式求解,二叉树的树形显示利用其对应满二叉树的位置输出。
代码:
#include <iostream>#include <iomanip>#include <cmath>using namespace std;typedef struct BinTreeNode * BinTree;typedef struct BinTreeNode{char data;BinTree lChild,rChild;} BinTreeNode;int max(int a,int b){return a>b?a:b;}void BuildBinTree(BinTree *T){char item;cin>>item;if(item=='#'){*T = NULL;}else {*T = new BinTreeNode;(*T)->data = item; BuildBinTree(&((*T)->lChild));BuildBinTree(&((*T)->rChild));}}int Height(BinTree T){if (!T)return 0;return 1 + max(Height(T->lChild),Height(T->rChild));}void DestroyBinTree(BinTree *T){if(*T){DestroyBinTree(&((*T)->lChild));DestroyBinTree(&((*T)->rChild));delete (*T);*T = NULL;}} void ShowTreeMarker(int **m,int row,int col,char *s){int cnt = 0;for(int i=0;i<row;i++){for(int j=0;j<col;j++){if(m[i][j]) cout<<setw(2)<<s[cnt++];elsecout<<setw(2)<<' ';}cout<<endl;}}void MatCreate(int *c,int **m,int level){int i,j;int start,step;int len = (1<<level) - 1;m[0][len>>1] = 1;int d = len;int cnt = 0;for(i=1;i<level;i++){//the (i-1)th rowd = d>>1;start = (d>>1);//if (c[++cnt])//m[i][start] = 1;for(j=1;j<=(1<<i);j++)if(c[++cnt]) m[i][start+(d+1)*(j-1)] = 1;}}void Pave(BinTree T,int *c,int start){if(T){c[start] = 1;Pave(T->lChild, c, 2 * start + 1);Pave(T->rChild, c, 2 * start + 2);}}int main(){BinTree T = NULL;BuildBinTree(&T);int h = Height(T);int len = (1<<h) - 1;int *c = new int[len];memset(c,0,len*sizeof(int));Pave(T,c,0);for(int i = 0; i < len; i++)cout<<c[i]<<" ";cout<<endl; cout<<"Height of BinTree : "<<h<<endl;cout<<(1<<h) - 1<<endl;int **m = new int*[h];for(int i= 0;i<h;i++){m[i] = new int[len];memset(m[i],0,len*sizeof(int));}MatCreate(c,m,h);for(int i=0;i<h;i++){for(int j=0;j<len;j++)cout<<setw(2)<<m[i][j];cout<<endl;}ShowTreeMarker(m,h,len,"ABCDEFGHIJK");DestroyBinTree(&T);}测试输入:
ABD##E##CF###
测试输出:
1 1 1 1 1 1 0 Height of BinTree : 37 0 0 0 1 0 0 0 0 1 0 0 0 1 0 1 0 1 0 1 0 0 A B C D E F
0 0
- 求二叉树的高度以及二叉树的树形显示
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 数据结构_求二叉树的高度以及层次遍历二叉树算法_C语言源代码
- 求二叉树的高度(非递归)
- 递归求二叉树的高度
- 二叉排序树_求二叉树的高度
- java 中的编码格式
- java安全之加密(对称与非对称)
- 2. PHP 特殊的流程控制语句
- The Difference Between Ruby Symbols and Strings
- Struts2控制文件上传
- 求二叉树的高度以及二叉树的树形显示
- S5PV210——bootloader
- PIC之休眠问题
- Qt笔记
- 理解Ruby的4种闭包:blocks, Procs, lambdas 和 Methods。
- 新手使用QT开发常会碰到的问题
- LNG工程机械优势明显 未来前途广阔
- BZOJ1196
- 移动开发团队的测试实践