跳到正文

题解

题解:P15801 [GESP202603 六级] 完全二叉树

ALEEN_OvO约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年3月21日
更新
2026年3月22日
篇幅
约 4 分钟
题目
P15801

版本

  1. v2当前
  2. v1

题目分析

我们有一棵以 11 为根的有根二叉树,每个结点 ii 有左儿子 lil_i 和右儿子 rir_i(00 表示不存在)。需要统计所有子树中,有多少棵子树是 完全二叉树。

完全二叉树的定义

在本题中,完全二叉树是指:

  1. 除了最后一层,其他层都是满的;
  2. 最后一层的结点都靠左排列。

等价地,我们可以用递归的方式判断一棵子树是否为完全二叉树:

  • 如果当前结点是叶子,它是完全二叉树。
  • 否则,左右子树都是完全二叉树,且满足以下之一:
    1. 左右子树深度相同,且左子树是满二叉树(所有层满),右子树可以是满二叉树或完全二叉树但最后一层靠右空;
    2. 左子树深度比右子树深 11,且右子树是满二叉树。

状态设计

我们定义每个结点的状态:

  • 状态 1:满二叉树(所有层满)
  • 状态 2:完全二叉树但不是满二叉树
  • 状态 3:不是完全二叉树

同时记录每个结点的深度。

转移规则

设当前结点为 uu,左儿子为 LL,右儿子为 RR。

  • 如果 LL 或 RR 状态为 33,则 uu 状态为 33。
  • 如果 dep[L]<dep[R]\text{dep}[L] < \text{dep}[R],则 uu 状态为 33。
  • 如果 dep[L]=dep[R]\text{dep}[L] = \text{dep}[R]:
    • 若 LL 状态为 11 且 RR 状态为 11,则 uu 状态为 11。
    • 若 LL 状态为 11 且 RR 状态为 22,则 uu 状态为 22。
    • 其他情况,uu 状态为 33。
  • 如果 dep[L]=dep[R]+1\text{dep}[L] = \text{dep}[R] + 1:
    • 若 RR 状态为 11,则 uu 状态为 22。
    • 否则 uu 状态为 33。
  • 如果 dep[L]>dep[R]+1\text{dep}[L] > \text{dep}[R] + 1,则 uu 状态为 33。

时间复杂度

一次 DFS 遍历所有结点,O(n)O(n),可以处理 n≤105n \le 10^5 的数据。


代码实现

C++
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, tp[N], dep[N], cnt;
struct node {
    int l, r;
} t[N];

void dfs(int u) {
    if (t[u].l == 0 && t[u].r == 0) {
        dep[u] = 1;
        tp[u] = 1;
        return;
    }
    if (t[u].l) dfs(t[u].l);
    if (t[u].r) dfs(t[u].r);

    dep[u] = max(dep[t[u].l], dep[t[u].r]) + 1;

    if (tp[t[u].l] == 3 || tp[t[u].r] == 3 || dep[t[u].l] > dep[t[u].r] + 1) {
        tp[u] = 3;
        return;
    }

    if (dep[t[u].l] < dep[t[u].r]) {
        tp[u] = 3;
        return;
    }

    if (dep[t[u].l] == dep[t[u].r]) {
        if (tp[t[u].l] == 1 && tp[t[u].r] == 1) tp[u] = 1;
        else if (tp[t[u].l] == 1 && tp[t[u].r] == 2) tp[u] = 2;
        else tp[u] = 3;
        return;
    }

    if (dep[t[u].l] == dep[t[u].r] + 1) {
        if (tp[t[u].r] == 1) tp[u] = 2;
        else tp[u] = 3;
        return;
    }
}

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> t[i].l >> t[i].r;
    }
    dfs(1);
    for (int i = 1; i <= n; i++) {
        if (tp[i] <= 2) cnt++;
    }
    cout << cnt << "\n";
    return 0;
}

总结

本题的关键在于递归判断子树是否为完全二叉树,通过记录深度和状态(满、完全、非完全)来避免重复计算,实现 O(n)O(n) 的高效解法。

对于每一棵子树,我们只需要检查左右子树的深度差和状态,就能递推出当前结点的状态,最后统计所有状态为 11 或 22 的结点数即可。

原文