上一次六级 P15801 GESP202603 六级] 完全二叉树 的弱化版。
解题思路
一个子树是不是满二叉树是由他的两个儿子决定的,故考虑从下往上递推。
如果一个节点 存在左儿子 、存在右儿子 、 子树大小相同且都是满二叉树,那么 也是满二叉树。
特别的,叶子也是满二叉树。
那么我们可以用 来标记点 是否是满二叉树,用 来标记以 为根的子树的高度。
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;
}