跳到正文

题解

题解:P17013 [GESP202606 六级] 满二叉树

FJ_EYoungOneC约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年7月6日
更新
2026年7月7日
篇幅
约 3 分钟
获赞
6
题目
P17013

版本

  1. v1当前

上一次六级 P15801 GESP202603 六级] 完全二叉树 的弱化版。

解题思路

一个子树是不是满二叉树是由他的两个儿子决定的,故考虑从下往上递推。

如果一个节点 uu 存在左儿子 aa、存在右儿子 bb、a,ba, b 子树大小相同且都是满二叉树,那么 uu 也是满二叉树。

特别的,叶子也是满二叉树。

那么我们可以用 is_full[x]is\_full[x] 来标记点 xx 是否是满二叉树,用 h[x]h[x] 来标记以 xx 为根的子树的高度。

AC_Code(Python)

Python
import sys
sys.setrecursionlimit(1000000)

n = int(input())
h = [0 for i in range(n + 1)]
is_full = [False for i in range(n + 1)]

l, r = [0], [0]
for i in range(n):
    x, y = map(int, input().split())
    l.append(x)
    r.append(y)

def dfs(u):
    a, b = l[u], r[u]
    if a:
        dfs(a)
    if b:
        dfs(b)
    h[u] = max(h[a], h[b]) + 1
    is_full[u] = is_full[a] and is_full[b] and h[a] == h[b]

is_full[0] = True
dfs(1)

res = 0
for i in range(1, n + 1):
    res += is_full[i]
print(res)

AC_Code(C++)

C++
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1e5 + 10;

int n;
bool is_full[N];
int h[N];
int l[N], r[N];

void dfs(int u)
{
    int a = l[u], b = r[u];
    if (a)
        dfs(a);
    if (b)
        dfs(b);
    
    h[u] = max(h[a], h[b]) + 1;
    is_full[u] = is_full[a] && is_full[b] && h[a] == h[b];
}

int main()
{
    cin >> n;
    for (int i = 1; i <= n; ++ i )
        cin >> l[i] >> r[i];
    
    is_full[0] = true;
    dfs(1);
    
    int res = 0;
    for (int i = 1; i <= n; ++ i )
        res += is_full[i];
    cout << res << endl;
    
    return 0;
}
原文
存档评论4 条抓取于