这是一个用于计算二叉树高度的C++代码。它使用先序遍历的方式建立二叉树,并通过递归方式计算二叉树的高度。
代码中的Depth函数用于计算二叉树高度,你需要在指定位置填写代码实现该功能。以下是完整的代码:
#include<iostream>
#include <string.h>
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T,char S[],int &i)
{//先序建立二叉树
if(S[i]=='0')
T=NULL;
else
{
T=new BiTNode;
T->data=S[i];
CreateBiTree(T->lchild,S,++i);
CreateBiTree(T->rchild,S,++i);
}
}
int Depth(BiTree T)
{//二叉树高度的计算
if (T == NULL)
return 0;
int leftHeight = Depth(T->lchild);
int rightHeight = Depth(T->rchild);
return max(leftHeight, rightHeight) + 1;
}
int main()
{
char S[100];
while(cin>>S)
{
if(strcmp(S,"0")==0) break;
int i=-1;
BiTree T;
CreateBiTree(T,S,++i);
cout<<Depth(T)<<endl;
}
return 0;
}
你只需要在Depth函数中填写正确的代码来计算二叉树的高度即可。
内容由零声教学AI助手提供,问题来源于学员提问




