1. 程式人生 > >C語言二叉樹的建立以及輸出二叉樹的深度

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