1. 程式人生 > >【模板】二叉樹合集

【模板】二叉樹合集

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行指的是這個節點的左兒子和右兒子

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int n,maxw = 0,maxdeep = 0,tong[2005];
struct tree{
    int l,r;
}l[2005
]; void dfs(int p,int d){ if(p == 0) return ; tong[d] ++; maxdeep = max(d,maxdeep); maxw = max(maxw,tong[d]); dfs(l[p].l,d + 1); dfs(l[p].r,d + 1); } int main(){ scanf("%d",&n); for(int i = 1;i <= n;i ++) scanf("%d %d",&l[i].l,&l[i].r); dfs(1
,1); printf("%d %d\n",maxw,maxdeep); return 0; }

3143 二叉樹的序遍歷
時間限制: 1 s
空間限制: 32000 KB
題目等級 : 白銀 Silver

題目描述 Description
求一棵二叉樹的前序遍歷,中序遍歷和後序遍歷

輸入描述 Input Description
第一行一個整數n,表示這棵樹的節點個數。

接下來n行每行2個整數L和R。第i行的兩個整數Li和Ri代表編號為i的節點的左兒子編號和右兒子編號。

輸出描述 Output Description
輸出一共三行,分別為前序遍歷,中序遍歷和後序遍歷。編號之間用空格隔開。

樣例輸入 Sample Input
5

2 3

4 5

0 0

0 0

0 0

樣例輸出 Sample Output
1 2 4 5 3

4 2 5 1 3

4 5 2 3 1

資料範圍及提示 Data Size & Hint
n <= 16

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 20;
int n;
struct dot{
    int l,r;
}tree[MAXN];

void qian(int x){
    printf("%d ",x);
    if(tree[x].l)   qian(tree[x].l);
    if(tree[x].r)   qian(tree[x].r);
}

void zhong(int x){
    if(tree[x].l)   zhong(tree[x].l);
    printf("%d ",x);
    if(tree[x].r)   zhong(tree[x].r);
}

void hou(int x){
    if(tree[x].l)   hou(tree[x].l);
    if(tree[x].r)   hou(tree[x].r);
    printf("%d ",x);
}

int main(){
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
        scanf("%d%d",&tree[i].l,&tree[i].r);
    qian(1);puts("");
    zhong(1);puts("");
    hou(1);puts("");
    return 0;
}