题解:P17013 [GESP202606 六级] 满二叉树
FJ_EYoungOneC · · 题解
上一次六级 [P15801 GESP202603 六级] 完全二叉树](https://www.luogu.com.cn/problem/P15801) 的弱化版。
解题思路
一个子树是不是满二叉树是由他的两个儿子决定的,故考虑从下往上递推。
如果一个节点
特别的,叶子也是满二叉树。
那么我们可以用
AC_Code(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++)
#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;
}