# 树10——求二叉树的高度和宽度

code:

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef struct Node
{
char data;
struct Node* lchild, *rchild;

}BitNode,*BiTree;
void CreateBitTree(BiTree *T, char str[]);
void PrintLevel(BiTree T);
void CreateBitTree(BiTree *T, char str[])
{
char ch;
BiTree stack[MAXSIZE];
int top = -1;
int flag, k;
BitNode *p;
*T = NULL, k = 0;
ch = str[k];
while (ch!='\0')
{
switch (ch)
{
case '(':
stack[++top] = p;
flag = 1;
break;
case ')':
top--;
break;
case ',':
flag = 2;
break;

default:
p = (BiTree)malloc(sizeof(BitNode));
p->data = ch;
p->lchild = NULL;
p->rchild = NULL;
if (*T==NULL)
{
*T = p;
}
else
{
switch (flag)
{
case 1:
stack[top]->lchild = p;
break;
case 2:
stack[top]->rchild = p;
break;
}
}

}

ch = str[++k];
}
}
void TreePrint(BiTree T, int level)
{
int i;
if (T==NULL)
{
return;
}
TreePrint(T->rchild, level + 1);
for (i = 0; i < level;i++)
{
printf("    ");
}
printf("%c\n",T->data);
TreePrint(T->lchild, level + 1);
}

int BiTreeDepth(BiTree T)
{
if (T==NULL)
{
return 0;
}
return BiTreeDepth(T->lchild) > BiTreeDepth(T->rchild) ? 1 + BiTreeDepth(T->lchild) : 1 + BiTreeDepth(T->rchild);
}

int BiTreeWidth(BiTree T)
{
int front, rear, last, maxw, temp;
BiTree Q[MAXSIZE];
BitNode *p;
if (T==NULL)
{
return 0;
}
else
{
front = 1, rear = 1, last = 1;
temp = 0;
maxw = 0;
Q[rear] = T;
while (front<=last)
{
p = Q[front++];
temp++;
if (p->lchild!=NULL)
{
Q[++rear] = p->lchild;
}
if (p->rchild!=NULL)
{
Q[++rear] = p->rchild;
}
if (front>last)
{
last = rear;
if (temp>maxw)
{
maxw = temp;

}
temp = 0;
}
}

return maxw;
}

}

void main()
{
BiTree T;
char str[MAXSIZE];
cout << "请输入二叉树的广义表形式：" << endl;
cin >> str;
cout << "由广义表形式的字符串构造二叉树：" << endl;
CreateBitTree(&T, str);
cout << endl;
TreePrint(T, 1);
cout << endl;
cout << "这棵树的高度为：" << BiTreeDepth(T) << endl;
cout << "这棵树的最大宽度为：" << BiTreeWidth(T) << endl;
system("pause");
//A(B(D(H,I),E),C(F,G))
}

09-17 4万+
11-12 472
03-24 1728
04-23 5073
12-21 48
05-16 352
11-19 4219
08-05 93
10-23 2311
08-24 48
11-04 1235
12-20 2594
12-21 3436
02-10 2万+
11-21 613
09-12
03-15 744