问题描述
采用先序法建立一棵二叉树,设计求该二叉树的深度,二叉树的数据域类型为字符型,扩展二叉树的叶子结点用‘#’表示,要求可以求多棵二叉树的深度,当二叉树的深度为0时程序结束。
输入描述
循环输入多棵扩展二叉树的先序遍历序列,每棵树占一行,以回车结束,每棵二叉树中结点之间以空格隔开
输出描述
输出各二叉树的深度,每次输出后面都换行
输入样例
A B # # C D # E # F # # G H # I K # # # #
A B D H # # I # # E J # # K # # C F L # # M # # G N # # O # #
输出样例
6
4
0
#include<iostream>
using namespace std;
bool deepth = true;
struct Node
{
char data; //数据
Node *Lchild,*Rchild; //左右子树
};
int max(int a,int b)
{
return a>b?a:b; //深度是左右子树中深度的最大者
}
class Text
{
public :
Text(){
hl = 0; //左子树的深度
hr = 0; //右子树的深度
root = Creat(); //创建二叉树
};
~Text()
{
Release(root);
};
void PreOrder(){
PreOrder(root);
}
void Judge()
{
Judge(root);
};
int Deepth(Node *Max); //求左右子树的深度
Node *root;
int hl;
int hr;
private:
Node *Creat();
void Release(Node *Bt);
void PreOrder(Node *Bt);
void Judge(Node *Bt);
};
int Text::Deepth(Node *Max)
{
if(Max == NULL)
{
return 0;
}
else
{
hl = Deepth(Max->Lchild);
hr = Deepth(Max->Rchild);
return max(hl,hr)+1; //返回两者的最大者并加一
}
}
void Text::Judge(Node *Bt)
{
if(Bt == NULL) //如果输入的值构建出来的是空二叉树
{
deepth = false;
return;
}
}
void Text::PreOrder(Node *Bt)
{
if(Bt == NULL)
{
return;
}
else
{
PreOrder(Bt->Lchild);
PreOrder(Bt->Rchild);
}
}
void Text::Release(Node *Bt)
{
if(Bt == NULL)
{
return;
}
else
{
Release(Bt->Lchild);
Release(Bt->Rchild);
delete Bt;
}
}
Node* Text::Creat()
{
Node *Bt;
char ch;
cin >> ch;
if(ch == '#')
{
Bt = NULL;
}
else
{
Bt = new Node;
Bt->data = ch;
Bt->Lchild = Creat(); //递归创建左子树
Bt->Rchild = Creat(); //递归创建右子树
}
return Bt;
}
int main()
{
while(deepth)
{
Text T;
T.Judge();
cout << T.Deepth(T.root);
cout << endl;
}
return 0;
}