CODE[VS]1501 二叉樹最大寬度和高度

1501 二叉樹最大寬度和高度
時間限制: 1 s
空間限制: 128000 KB
題目等級 : 白銀 Silver
題解
題目描述 Description
給出一個二叉樹,輸出它的最大寬度和高度。

輸入描述 Input Description
第一行一個整數n。

下面n行每行有兩個數,對於第i行的兩個數,代表編號爲i的節點所連接的兩個左右兒子的編號。如果沒有某個兒子爲空,則爲0。

輸出描述 Output Description
輸出共一行,輸出二叉樹的最大寬度和高度,用一個空格隔開。

樣例輸入 Sample Input
5

2 3

4 5

0 0

0 0

0 0

樣例輸出 Sample Output
2 3

數據範圍及提示 Data Size & Hint
n<16

默認第一個是根節點

以輸入的次序爲編號

2-N+1行指的是這個節點的左孩子和右孩子

注意:第二題有極端數據!

1

0 0

這題你們別想投機取巧了,給我老老實實搜索!


#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
int MaxHeight = 0;
int Height = 0;
int treeNode[16][2] = { 0 };
int num[16] = { 0 };

struct Node//樹節點
{
	int data;
	int height;
	Node* left;
	Node* right;
};

typedef struct Node* Tree;

Tree Build(int x, Tree &t)//根據數組建樹
{

	if (x == 0)
	{
		t = NULL;
	}
	else
	{
		Height++;
		if (Height > MaxHeight)
			MaxHeight = Height;
		t = (Tree)malloc(sizeof(Node));
		t->data = x;
		t->height = Height;
		Build(treeNode[x][0], t->left);
		Build(treeNode[x][1], t->right);
		Height--;
	}
	return t;
}

void view(Tree &t)
{
	if (t == NULL)
		return;
	else
	{
		view(t->left);
		num[t->height]++;
		view(t->right);
	}
}

int main()
{
	int n;
	while (scanf("%d", &n) != EOF)
	{
		memset(num, 0, sizeof(int) * 16);
		MaxHeight = 0;
		Height = 0;
		int findRoot[16] = { 0 };
		int i,maxNum=0;
		for (i = 1; i <= n; ++i)
		{
			scanf("%d%d", &treeNode[i][0], &treeNode[i][1]);
			findRoot[treeNode[i][0]] = 1;
			findRoot[treeNode[i][1]] = 1;
		}
		for (i = 1; i <= n; i++)
		{
			if (findRoot[i] == 0)
				break;
		}
		Tree t;
		t = Build(i, t);
		view(t);
		for (i = 1; i <= n; i++)
		{
			if (num[i] > maxNum)
				maxNum = num[i];
		}
		printf("%d %d\n", maxNum, MaxHeight);
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章