✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1110 Complete Binary Tree (pintia.cn)
🔑中文翻译:完全二叉树
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
Given a tree, you are supposed to tell if it is a complete binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤20) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a
-will be put at the position. Any pair of children are separated by a space.Output Specification:
For each case, print in one line
YESand the index of the last node if the tree is a complete binary tree, orNOand the index of the root if not. There must be exactly one space separating the word and the number.Sample Input 1:
9 7 8 - - - - - - 0 1 2 3 4 5 - - - -Sample Output 1:
YES 8Sample Input 2:
8 - - 4 5 0 6 - - 2 3 - 7 - - - -Sample Output 2:
NO 1
给定一棵二叉树,第一行给定 N N N ,表示有 N N N 个结点,且结点编号为 0 ∼ N − 1 0\sim N-1 0∼N−1 。
接下来
N
N
N 行输入
0
∼
N
−
1
0\sim N-1
0∼N−1 个结点的左右孩子编号,空结点用 - 表示。
判断该二叉树是否是完全二叉树,如果是则输出 YES 和完全二叉树的最后一个结点编号,否则输出 NO 和该树的根结点编号。
k (假设下标从 1 开始),则满足以下条件:
k * 2k * 2 + 1我们拿题目的第一个样例举例,可以得到下面这颗完全二叉树:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sUsGxE2D-1664376281707)(PAT 甲级辅导.assets/7.png)]](https://1000bd.com/contentImg/2024/09/12/941576bed4400aaa.png)
其在一维数组中的存储情况为:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-u2kfddcr-1664376281712)(PAT 甲级辅导.assets/8.png)]](https://1000bd.com/contentImg/2024/09/12/be763b884b1f9d75.png)
#include
using namespace std;
const int N = 25;
int l[N], r[N], has_parent[N];
int n, max_k, max_id;
void dfs(int u, int k)
{
if (u == -1) return;
//如果当前遍历到的下标k更大,则进行更新
if (k > max_k)
{
max_k = k; //找到最后一个结点在一维数组中的下标
max_id = u; //找到最后一个结点的编号
}
dfs(l[u], k * 2);
dfs(r[u], k * 2 + 1);
}
int main()
{
//初始化
cin >> n;
memset(l, -1, sizeof l);
memset(r, -1, sizeof r);
//输入结点信息
for (int i = 0; i < n; i++)
{
string a, b;
cin >> a >> b;
if (a != "-") l[i] = stoi(a), has_parent[l[i]] = true;
if (b != "-") r[i] = stoi(b), has_parent[r[i]] = true;
}
//找到根结点下标
int root = 0;
while (has_parent[root]) root++;
dfs(root, 1);
if (max_k == n) printf("YES %d\n", max_id);
else printf("NO %d\n", root);
return 0;
}