Public feed #3YKqDTLAum

text paste

public text v1 · immutable
Raw Edit
·published 2026-12-01 07:59 UTC
rendered paste body
#include <iostream>#include <vector>#include <algorithm>using namespace std;// 定义二叉树节点结构struct TreeNode {    int val;    TreeNode *left;    TreeNode *right;    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}};// 全局变量存储输入数据int n;vector<int> in_order;vector<int> post_order;bool is_complete = true; // 标记是否为完全二叉树// 根据中序和后序序列重建二叉树// in_l, in_r: 当前子树在中序序列中的左右边界(闭区间)// post_l, post_r: 当前子树在后序序列中的左右边界(闭区间)TreeNode* buildTree(int in_l, int in_r, int post_l, int post_r) {    if (in_l > in_r) return nullptr; // 递归终止条件:空区间    // 后序序列的最后一个元素是根节点    int root_val = post_order[post_r];    TreeNode* root = new TreeNode(root_val);    // 在中序序列中找到根节点的位置    int root_idx = -1;    for (int i = in_l; i <= in_r; ++i) {        if (in_order[i] == root_val) {            root_idx = i;            break;        }    }    // 题目保证输入合理,root_idx必能找到    // 计算左子树的节点个数    int left_size = root_idx - in_l;    // 递归构建左子树    // 中序范围: [in_l, root_idx - 1]    // 后序范围: [post_l, post_l + left_size - 1]    root->left = buildTree(in_l, root_idx - 1, post_l, post_l + left_size - 1);    // 递归构建右子树    // 中序范围: [root_idx + 1, in_r]    // 后序范围: [post_l + left_size, post_r - 1] (注意post_r是根,已排除)    root->right = buildTree(root_idx + 1, in_r, post_l + left_size, post_r - 1);    return root;}// DFS遍历树并检查节点编号// u: 当前节点指针// id: 当前节点在完全二叉树数组中的下标(从1开始)void checkComplete(TreeNode* u, long long id) {    if (!u) return;    if (!is_complete) return; // 若已判定不是,则直接返回    if (id > n) {        is_complete = false; // 发现编号超过节点总数,说明有空洞        return;    }    checkComplete(u->left, id * 2);    checkComplete(u->right, id * 2 + 1);}int main() {    // 优化I/O操作    ios::sync_with_stdio(false);    cin.tie(nullptr);    if (!(cin >> n)) return 0; // 读取结点数    in_order.resize(n);    post_order.resize(n);    for (int i = 0; i < n; ++i) cin >> in_order[i];    for (int i = 0; i < n; ++i) cin >> post_order[i];    // 1. 重建二叉树    TreeNode* root = buildTree(0, n - 1, 0, n - 1);    // 2. 判定完全二叉树    checkComplete(root, 1); // 根节点编号为1    if (is_complete) {        cout << "Yes" << endl;    } else {        cout << "No" << endl;    }    // 释放内存(可选,竞赛中通常忽略)    // ...    return 0;}