✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1110 Complete Binary Tree (pintia.cn)
🔑中文翻译:完全二叉树
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
1110 Complete Binary Tree
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
YES
and the index of the last node if the tree is a complete binary tree, orNO
and 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 8
Sample 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 * 2
- 该结点的右孩子下标为
k * 2 + 1
- 该结点的左孩子下标为
- 所以如果一个二叉树是完全二叉树的话,将它所有结点按上述方式存储到一维数组中是可以刚好填满 1 ∼ N 1\sim N 1∼N(下标从 1 1 1 开始)个位置的。相反如果不是完全二叉树,则 1 ∼ N 1\sim N 1∼N 个位置中会有空余,也就是说最后一个结点的位置会大于 N N N 。故我们只用判断最后一个结点的位置是否为 N N N 即可,如果是 N N N 则说明是完全二叉树。
- 最后输出判断结果,注意如果是完全二叉树还需要输出最后一个结点的编号,否则输出该树的根结点编号。
我们拿题目的第一个样例举例,可以得到下面这颗完全二叉树:
其在一维数组中的存储情况为:
代码
#include<bits/stdc++.h>
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;
}