基于二叉链表的二叉树高度的计算
描述
设二叉树中每个结点的元素均为一个字符,按先序遍历的顺序建立二叉链表,,编写递归算法计算二叉树的高度。
输入
多组数据。每组数据一行,为二叉树的前序序列(序列中元素为‘0’时,表示该结点为空)。当输入只有一个“0”时,输入结束。
输出
每组数据分别输出一行,为二叉树的高度。
输入样例 1
abcd00e00f00ig00h00 abd00e00cf00g00 0
输出样例 1
4 3
#include<iostream>
using namespace std;
#define Maxsize 100
typedef struct BiNode {
char data;
BiNode* lchild, * rchild;
}BiNode,*BiTree;
void Create(BiTree& t,char a[],int &i) {//递归建立二叉链树
if (a[i] == '0') {
t = NULL;
}
else {
t = new BiNode;
t->data = a[i];
Create(t->lchild, a, ++i);
Create(t->rchild, a, ++i);
}
}
int high(BiTree& t) {
if (t == NULL) {
return 0;
}
int lhigh = high(t->lchild);
int rhigh = high(t->rchild);
if (lhigh > rhigh) {
return lhigh + 1;
}
else {
return rhigh + 1;
}
}
int main() {
char a[1000];
while (cin>>a&&a[0]!='0') {
int i = -1;
BiTree t;
Create(t, a, ++i);
cout << high(t) << endl;
}
return 0;
}