C语言二叉树的建立以及输出二叉树的深度

二叉树的深度(10分)

题目内容:

给定一棵二叉树,求该二叉树的深度

二叉树深度定义:从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的节点个数为树的深度

输入格式:

第一行是一个整数n,表示二叉树的结点个数。二叉树结点编号从1到n,根结点为1,n <= 10

接下来有n行,依次对应二叉树的n个节点。

每行有两个整数,分别表示该节点的左儿子和右儿子的节点编号。如果第一个(第二个)数为-1则表示没有左(右)儿子

输出格式:

输出一个整型数,表示树的深度

输入样例:

3
2 3
-1 -1
-1 -1

输出样例:

2

代码

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode 
{
	ElementType Data;
	BinTree Left;
	BinTree Right;
};


int GetHeight(BinTree BT);

int main()
{
	TNode T[20];
	for (int i = 0; i < 20; i++)
	{
		T[i].Data = 0;
		T[i].Left = NULL;
		T[i].Right = NULL;
	}
	int n, tempr, templ;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d %d", &templ, &tempr);
		if (templ != -1)
			T[i].Left = &T[templ];
		else
			T[i].Left = NULL;
		if (tempr != -1)
			T[i].Right = &T[tempr];
		else
			T[i].Right = NULL;
	}
	printf("%d\n", GetHeight(&T[1]));
	
	system("pause");
	return 0;
}

int GetHeight(BinTree BT)
{
	int lh, rh;
	if (BT == NULL)
		return 0;
	lh = GetHeight(BT->Left);
	rh = GetHeight(BT->Right);
	
	return (lh > rh ? lh : rh) + 1;
}

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/84067944
今日推荐