标签:
只过了20%...我日
树的高度
时间限制:C/C++语言 1000MS;其他语言 3000MS
内存限制:C/C++语言 65536KB;其他语言 589824KB
题目描述:
现在有一棵合法的二叉树,树的节点都是用数字表示,
现在给定这棵树上所有的父子关系,求这棵树的高度
输入
输入的第一行表示节点的个数n(1<=n<=1000,节点的编号为0到n-1)组成,
下面是n-1行,每行有两个整数,第一个数表示父节点的编号,第二个数表示子节点的编号
输出
输出树的高度,为一个整数
样例输入
5
0 1
0 2
1 3
1 4
样例输出
3
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <malloc.h> 4 #include <bits/stdc++.h> 5 6 using namespace std; 7 8 void SortTwoArray(int* parent, int* node, int length) 9 { 10 int temp1; 11 int temp2; 12 for (int i = 0; i < length; ++i) 13 { 14 for (int j = 0; j < length - i; ++j) 15 { 16 if (node[j] > node[j+1]) 17 { 18 temp1 = node[j+1]; 19 node[j+1] = node[j]; 20 node[j] = temp1; 21 22 temp2 = parent[j+1]; 23 parent[j+1] = parent[j]; 24 parent[j] = temp2; 25 } 26 } 27 } 28 } 29 30 // 二分查找 31 int Binary_Search(int* nums, int length, int key) 32 { 33 int left, right, middle; 34 left = 0; 35 right = length - 1; 36 37 while (left <= right) 38 { 39 middle = (left + right) / 2; 40 if (key < nums[middle]) 41 { 42 right = middle - 1; 43 } 44 else if (key > nums[middle]) 45 { 46 left = middle + 1; 47 } 48 else 49 { 50 return middle; 51 } 52 } 53 return -1; 54 } 55 56 57 int main() 58 { 59 int n; 60 while (scanf("%d", &n) != EOF) 61 { 62 if (n == 1) 63 { 64 int a, b; 65 scanf("%d %d", &a, &b); 66 printf("1\n"); 67 continue; 68 } 69 int length = n - 1; 70 int* parent = (int*)malloc(sizeof(int)*length); 71 int* node = (int*)malloc(sizeof(int)*length); 72 for (int i = 0; i < length; ++i) 73 { 74 scanf("%d", &parent[i]); 75 scanf("%d", &node[i]); 76 } 77 SortTwoArray(parent, node, length); 78 int height = 1; 79 int Num = node[length - 1]; 80 while (Num != 0) 81 { 82 int pos = Binary_Search(node, length, Num); 83 Num = parent[pos]; 84 height ++; 85 } 86 printf("%d\n", height); 87 free(parent); 88 free(node); 89 } 90 return 0; 91 }
标签:
原文地址:http://www.cnblogs.com/Juntaran/p/5901683.html