采用先序法建立一棵二叉树,设计求该二叉树的深度,二叉树的数据域类型为字符型,扩展二叉树的叶子结点用‘#’表示,要求可以求多棵二叉树的深度,当二叉树的深度为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
解题思路:
遍历二叉树两支,lnum表示左半支的最深处,rnum表示右半支的最深处,最后比较lnum和rnum输出最大值,即为二叉树深度。
代码:
int BiTree::GetDeep(BiNode*bt){
if(bt==NULL)return 0;
int lNum=1;
int rNum=1;
int val;
lNum+=GetDeep(bt->lchild);
rNum+= GetDeep(bt->rchild);
val=lNum>rNum?lNum:rNum;
return val;
}
完整代码:
#include <iostream>
#include<cmath>
using namespace std;
struct BiNode{
char data;
BiNode *lchild;
BiNode *rchild;
};
class BiTree{
public:
BiTree(){root=Creat();}
~BiTree(){Release(root);}
int GetDeep(){return GetDeep(root);}
private:
BiNode *root;
BiNode *Creat();
void Release(BiNode *bt);
int GetDeep(BiNode*bt);
};
int BiTree::GetDeep(BiNode*bt){
if(bt==NULL)return 0;
int lNum=1;
int rNum=1;
int val;
lNum+=GetDeep(bt->lchild);
rNum+= GetDeep(bt->rchild);
val=lNum>rNum?lNum:rNum;
return val;
}
BiNode* BiTree::Creat(){
BiNode *bt;
char ch;
cin >> ch;
if (ch == '#')bt = NULL;
else {
bt = new BiNode;
bt->data = ch;
bt->lchild = Creat();
bt->rchild = Creat();
}
return bt;
}
void BiTree::Release(BiNode *bt){
if(bt!=NULL){
Release(bt->lchild);
Release(bt->rchild);
delete bt;
}
}
int main()
{
bool i= true;
while(i)
{
BiTree A;
if(A.GetDeep()==0)i= false;
cout<<A.GetDeep();
}
}