题目:
代码:
#include<iostream>
using namespace std;
typedef struct BinaryTree
{
char data;
struct BinaryTree* left;
struct BinaryTree* right;
}BT;
void BinaryTreeCreate(BT*& ps)
{
char a;
cin >> a;
if (a == '#')
ps = NULL;
else
{
ps = (BT*)malloc(sizeof(BT));
ps->data = a;
BinaryTreeCreate(ps->left);
BinaryTreeCreate(ps->right);
}
}
int BinaryTreeDepth(BT* ps)
{
if (ps == NULL)
return 0;
else
{
int leftDepth = BinaryTreeDepth(ps->left);//左子树的深度
int rightDepth = BinaryTreeDepth(ps->right);//右子树的深度
return leftDepth>rightDepth ? leftDepth + 1 : rightDepth + 1;
//运用三目运算符,如果左子树深度更大则最大深度为左子树+1,否则相反
}
}
int main()
{
BT* tree;
BinaryTreeCreate(tree);
printf("%d", BinaryTreeDepth(tree));
return 0;
}