求二叉树的深度 题目编号:376
采用先序法建立一棵二叉树,设计求该二叉树的深度,二叉树的数据域类型为字符型,扩展二叉树的叶子结点用‘#’表示,要求可以求多棵二叉树的深度,当二叉树的深度为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;
static int count=0,h1=0,h2=0;
struct Node
{
char data;
Node *Lchild,*Rchild;
};
int max(int a,int b)
{
return a>b?a:b;
}
class BiTree
{
public:
BiTree(){root=Create(root);}
~BiTree(){Release(root);}
int print(){print(root);}
int null(){(null(root)); }
private:
Node *root;
Node *Create(Node *bt);
void Release(Node *bt);
int print(Node *bt);
int null(Node *bt);
Node *s[100];
};
Node*BiTree::Create(Node *bt)
{
char s;
cin>>s;
if(s=='#')
bt=NULL;
else{
bt=new Node;
bt->data=s;
count++;
bt->Lchild=Create(bt->Lchild);
bt->Rchild=Create(bt->Rchild);
}
return bt;
}
void BiTree::Release(Node *bt)
{
if(bt!=NULL){
Release(bt->Lchild);
Release(bt->Rchild);
delete bt;
}
}
int BiTree::null(Node *bt)
{
if(bt == NULL)
{
return 1;
}
else
{
return 0;
}
}
int BiTree::print(Node *bt)
{
if(bt == NULL)
{
return 0;
}
else
{
h1=print(bt->Lchild);
h2=print(bt->Rchild);
return max(h1,h2)+1;
}
}
int main()
{
int j;
while(1)
{
BiTree T;
int i = T.null();
if(i == 1)
{
cout << "0" << endl ;
break;
}
else
{
j=T.print();
cout<<j;
}
cout << endl;
}
return 0;
}