NOJ1019 计算二叉树的高度和结点数

这可真够烦的…

#include<stdio.h>
#include<stdlib.h>
typedef char ElemType;
int n=0;
typedef struct BinaryTreeNode
{
	ElemType Data;
	struct BinaryTreeNode *lChild, *rChild;
}BinaryTreeNode;
typedef BinaryTreeNode* BiTree;
typedef struct BinaryTree{
	BinaryTreeNode *root;
}BinaryTree;
void PreOrderTransverse(BiTree t)
{
	if (t == NULL)
		return;
	n++;
	printf(" %c", t->Data);
	PreOrderTransverse(t->lChild);
	PreOrderTransverse(t->rChild);
}
void InOrderTransverse(BiTree t)
{
	if (t == NULL)
		return;
	InOrderTransverse(t->lChild);
	printf(" %c", t->Data);
	InOrderTransverse(t->rChild);
}
void PostOrderTransverse(BiTree t)
{
	if (t == NULL)
		return;
	PostOrderTransverse(t->lChild);
	PostOrderTransverse(t->rChild);
	printf(" %c", t->Data);
}
BinaryTreeNode* PreCreateBt(BinaryTreeNode *t)
{
	char ch;
	ch = getchar();
	getchar();
	if (ch == '#')
		t = NULL;
	else
	{
		t = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode));
		t->Data = ch;
		t->lChild = PreCreateBt(t->lChild);
		t->rChild = PreCreateBt(t->rChild);
	}

	return t;
}
int Max(int a, int b)
{
	return a >= b ? a : b;
}
int SizeH(BinaryTree Bt)
{
	return SizeofHigh(Bt.root);
}
int SizeofHigh(BinaryTreeNode *p)
{
	if (p == NULL)
		return 0;
	if (p->lChild == NULL && p->rChild == NULL)
		return 1;
	return Max(SizeofHigh(p->lChild), SizeofHigh(p->rChild)) + 1;
}
int SizeL(BinaryTree Bt)
{
	return SizeofLeaf(Bt.root);
}
int SizeofLeaf(BinaryTreeNode *p)
{
	if (!p)
		return 0;
	if ((!(p->lChild)) && (!(p->rChild)))
		return 1;
	return SizeofLeaf(p->lChild) + SizeofLeaf(p->rChild);
}
int main()
{
	BinaryTree myTree;
	int n0, n1, n2,h;
	myTree.root = NULL;
	myTree.root = PreCreateBt(myTree.root);
	printf("PreOrder:");
	PreOrderTransverse(myTree.root);
	printf("\n");
	printf("InOrder:");
	InOrderTransverse(myTree.root);
	printf("\n");
	printf("PostOrder:");
	PostOrderTransverse(myTree.root);
	printf("\n");
	h = SizeH(myTree);
	printf("%d\n", h);
	n0 = SizeL(myTree);
	if (h == 0)
		n0 = n1 = n2 = 0;
	else
	{
		n2 = n0 - 1;
		n1 = n - n0 - n2;
	}
		printf("%d %d %d\n",n, n0,n1);
	return 0;
}

NOJ1019 计算二叉树的高度和结点数》有1个想法

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注