二叉樹最大寬度和高度 時間限制: 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這題你們別想投機取巧了,給我老老實實搜索!
思路:沒啥思路,我就是造出一棵樹然后dfs搜索,求出寬度和高度。ps:說實話,這個寬度我搞了好久,寫重復了一個,弄的答案錯了!
代碼:(略長)
#include<iostream>#include<string.h>#include<math.h>#include<algorithm>using namespace std;struct tree{//樹 int num; struct tree *leftT; struct tree *rightT;};struct tree *p;//指向當前需要的樹節點void find(struct tree *tr, int i){ if (tr->num == i){ p = tr; return; } if (tr->leftT)find(tr->leftT, i); if (tr->rightT)find(tr->rightT, i);}//計算深度 int deepth(struct tree *tr){ if (!tr)return 0; int m = max(deepth(tr->leftT)+1, deepth(tr->rightT) + 1); return m;}int a[100], maxs = 1;//默認maxs的寬度為1,為根節點//計算寬度void width(struct tree * tr, int i){ if (!tr)return; if (tr->leftT)a[i + 1]++; if (tr->rightT)a[i + 1]++; if (maxs<a[i + 1])maxs = a[i + 1]; width(tr->leftT, i + 1); width(tr->rightT, i + 1);}void dfs(struct tree *tr, int i){ int n, m; cin >> n >> m; if (n == 0 && m == 0)return; find(tr, i); if (n > 0){ p->leftT = new tree; p->leftT->num = n; p->leftT->leftT = NULL; p->leftT->rightT = NULL; } if (m > 0){ p->rightT = new tree; p->rightT->num = m; p->rightT->leftT = NULL; p->rightT->rightT = NULL; }}int main(){ a[1] = 1; int n; cin >> n; struct tree *tr = new tree; tr->num = 1; tr->leftT = NULL; tr->rightT = NULL; for (int i = 1; i <= n; i++){ dfs(tr, i); } int deep = deepth(tr); width(tr, 1); cout << maxs << " " << deep << endl; return 0;}新聞熱點
疑難解答