跳到主内容
paste
bin
.ca
type · paste · share
⌘
K
系列
bin 系列
pastebin.ca
中心
Share text and code with expiry and privacy controls.
imagebin.ca
Upload and share images with direct links.
filebin.ca
Drop a file and get a shareable link.
notebin.ca
Write Markdown notes with durable links.
turl.ca
Short, reputation-checked links.
attn.ca
Notifications and alerts for your services.
voicebin.ca
Record and share short voice clips.
dnsbin.ca
Inspect DNS and debug records.
登录
?
账户
更多
▾
文档
← 返回文本
›
编辑 / 分支
无标题文本
#3YKqDTLAum
public / public
新版本
匿名
已创建 3 days ago
过期于 4 days
2.7 KB
语法:
text
你的更改会创建一个链接到此文本的新文本 — 原始文本不变。
新版本
你的更改会创建一个链接到此文本的新文本 — 原始文本不变。
标题(可选)
文件名
语法
text
text
bash
c
cpp
css
diff
dockerfile
go
html
ini
java
javascript
json
kotlin
lua
makefile
markdown
nginx
php
python
ruby
rust
shellscript
sql
swift
toml
typescript
xml
yaml
可见性
公开动态
访问
public
过期
7 天
10 分钟
1 小时
1 天
7 天
30 天
90 天
自定义…
自定义过期
变更备注
(可选)
任何人都能在公开动态中找到此文本。选择“未列出”即可仅通过链接分享。
创建新版本
取消
粘贴或输入…
#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; }