小米2017校招筆試題

來源:互聯網
上載者:User

標籤:

只過了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         else49         {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 }

 

小米2017校招筆試題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.