设有一棵二叉树,其结点值为字符型并假设各值互不相等,采用二叉链表存储表示。现输入其扩展二叉树的前序遍历序列,要求建立该二叉树,并求其高度。
输入格式:
第一行为一个整数n,表示以下有n组数据,每组数据为扩展二叉树的前序遍历序列。
输出格式:
每组输出占一行,输出该二叉树的高度。
输入样例:
在这里给出一组输入。例如:
2
AB#D##C##
ABD##E##C#F##
结尾无空行
输出样例:
在这里给出相应的输出。例如:
3
3
结尾无空行
C++采用递归的思想:
#include<iostream>
using namespace std;
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}*BiTree,BiTNode;
void CreatTree(BiTree &T){
char ch;
cin>>ch;
if(ch=='#'){
T=NULL;
}
else{
T = new BiTNode;
T->data=ch;
CreatTree(T->lchild);
CreatTree(T->rchild);
}
}
int GetHeight(BiTree T){
int ldepth,rdepth;
if(T==NULL){
return 0;
}
else{
ldepth=GetHeight(T->lchild);
rdepth=GetHeight(T->rchild);
return ldepth>rdepth?ldepth+1:rdepth+1;//因为有根节点,所以要加一
}
}
int main(){
int n;
cin>>n;
while(n--){
BiTree T;
CreatTree(T);
cout<<GetHeight(T)<<endl;
}
return 0;
}