数据结构之971: 统计利用先序遍历创建的二叉树的深度

题目:

数据结构之971: 统计利用先序遍历创建的二叉树的深度_第1张图片

 

代码:

#include
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;
}

你可能感兴趣的:(数据结构SWUSTOJ,算法)