题解:P15801 [GESP202603 六级] 完全二叉树
题目大意
求出给定有根树的所有 n 棵子树中,有多少棵子树是完全二叉树。
思路
暴力将所有子树判断是否是完全二叉树时间复杂度大概在O(n^2),严重超时。但不难发现根为节点i的二叉树是否是完全二叉树与l[i]和r[i]为根节点的二叉树有关,如下:
1 左子树与右子树全等且均为满二叉树,该子树为满二叉树
2 左子树为满二叉树,右子树亦为满二叉树,左子树深度比右子树深度大一,该子树为完全二叉树
3 左子树为完全二叉树,右子树为满二叉树,左子树深度比右子树深度大一,该子树为完全二叉树
4 左子树为满二叉树,右子树为完全二叉树,左子树深度=右子树深度,该子树为完全二叉树
(注;一棵树的深度为其最深节点的深度,叶子节点与空点都是满二叉树,空点深度=其父亲节点深度)
接下来后序遍历即可,(bfs也可,读者若感兴趣请自行尝试)
AC code
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
// 存储每个节点的左右孩子(0表示无孩子)
vector<int> l(n + 1), r(n + 1);
for (int i = 1; i <= n; ++i) {
cin >> l[i] >> r[i];
}
// 初始化三个核心数组
vector<int> depth(n + 1, 0); // 子树深度
vector<bool> is_full(n + 1, false); // 是否是满二叉树
vector<bool> is_complete(n + 1, false); // 是否是完全二叉树
// 迭代式后序遍历(避免递归栈溢出)
stack<pair<int, bool>> st; // pair<节点编号, 是否已访问>
st.emplace(1, false);
while (!st.empty()) {
auto [u, visited] = st.top();
st.pop();
if (!visited) {
// 未访问过:重新压入(标记已访问),再压入右、左孩子(未访问)
st.emplace(u, true);
if (r[u] != 0) st.emplace(r[u], false);
if (l[u] != 0) st.emplace(l[u], false);
} else {
// 已访问过:处理当前节点
int left = l[u];
int right = r[u];
// 空节点的预设值:depth=0,is_full=true,is_complete=false
int d_left = (left == 0) ? 0 : depth[left];
int d_right = (right == 0) ? 0 : depth[right];
bool f_left = (left == 0) ? true : is_full[left];
bool f_right = (right == 0) ? true : is_full[right];
bool c_left = (left == 0) ? false : is_complete[left];
bool c_right = (right == 0) ? false : is_complete[right];
// 1. 计算当前子树深度
depth[u] = max(d_left, d_right) + 1;
// 2. 判断是否是满二叉树:左右都是满的,且深度相等
is_full[u] = (f_left && f_right) && (d_left == d_right);
// 3. 判断是否是完全二叉树
if (is_full[u]) {
// 满二叉树一定是完全二叉树
is_complete[u] = true;
} else {
// 检查另外三个条件
bool cond2 = f_left && f_right && (d_left == d_right + 1);
bool cond3 = c_left && f_right && (d_left == d_right + 1);
bool cond4 = f_left && c_right && (d_left == d_right);
is_complete[u] = cond2 || cond3 || cond4;
}
}
}
// 统计所有完全二叉树子树的数量
int ans = 0;
for (int i = 1; i <= n; ++i) {
if (is_complete[i]) ans++;
}
cout << ans << endl;
return 0;
}
望审核大大通过