PAT甲級1110 Complete Binary Tree (25分)|C++實現
一、題目描述
原題連結
Given a tree, you are supposed to tell if it is a complete binary tree.
Input Specification:
Output Specification:
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
二、解題思路
完全二叉樹填入陣列之後,父親結點和左右孩子的編號是有特定關係的(兩倍或兩倍加1),利用這個關係,我們只需要看dfs遍歷出來的最大編號等不等於N-1就可以知道是否為完全二叉樹。
三、AC程式碼
#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
struct Node
{
int id, parent=-1, left, right;
}node[25];
int maxn = -1, ans;
void dfs(int root, int index) //dfs,求出如果是完全二叉樹最後一個結點的編號
{
if(index > maxn)
{
maxn = index;
ans = root;
}
if(node[root].left != -1) dfs(node[root].left, index*2+1);
if(node[root].right != -1) dfs(node[root].right, index*2+2);
return;
}
bool check(string str)
{
for(int i=0; i<str.size(); i++)
{
if(str[i] == '-') return false;
}
return true;
}
int main()
{
int N;
string ch1, ch2;
scanf("%d", &N);
for(int i=0; i<N; i++)
{
getchar();
cin >> ch1 >> ch2;
node[i].id = i;
node[i].left = check(ch1) ? stoi(ch1) : -1;
node[i].right = check(ch2) ? stoi(ch2) : -1;
if(node[i].left != -1) node[node[i].left].parent = i;
if(node[i].right != -1) node[node[i].right].parent = i;
}
Node root;
for(int i=0; i<N; i++)
{
if(node[i].parent == -1) //parent==-1則為根結點
root = node[i];
}
dfs(root.id, 0);
bool flag = true;
if(maxn != N-1) flag = false; //如果最後一個元素的編號不是N-1,則不是完全二叉樹
flag ? printf("YES %d", ans) : printf("NO %d", root.id);
return 0;
}
相關文章
- (非原創)PAT甲級1123 Is It a Complete AVL Tree (30分)|C++實現C++
- PAT甲級1126~1130|C++實現C++
- PAT甲級1122 Hamiltonian Cycle (25分)|C++實現C++
- PAT甲級1154 Vertex Coloring (25分)|C++實現C++
- 【PAT甲級A1084】Broken Keyboard (20分)(c++)C++
- PAT甲級1032 Sharing
- 【PAT甲級A1038】Recover the Smallest Number (30分)(c++)C++
- PAT甲級1030 Travel Plan
- 浙大PAT甲級考試
- PAT甲級1023 Have Fun with Number
- 菜鳥記錄:c語言實現PAT甲級1010--RadixC語言
- LeetCode C++ 968. Binary Tree Cameras【Tree/DFS】困難LeetCodeC++
- 【PAT甲級A1065】A+B and C (64bit) (20分)(c++)C++
- PAT甲級-1015. Reversible Primes (20)
- PAT 甲級 1152 Google Recruitment (20分)GoUI
- 20年春季甲級pat考試
- Traversals of binary tree
- PAT甲級-1014. Waiting in Line (30)(模擬)AI
- 二叉搜尋樹(Binary Search Tree)(Java實現)Java
- PAT甲級真題1069 數字黑洞(巧妙解法)
- PAT甲級考試題庫題目分類
- Leetcode Binary Tree PathsLeetCode
- 2024 秋季PAT認證甲級(題解A1-A4)
- PAT甲級-1140. Look-and-say Sequence (20)(模擬)
- [LintCode] Check Full Binary Tree
- 257-Binary Tree Paths
- 543-Diameter of Binary Tree
- 563-Binary Tree Tilt
- 655-Print Binary Tree
- 654-Maximum Binary Tree
- 814-Binary Tree Pruning
- 110-Balanced Binary Tree
- 545. Boundary of Binary Tree
- 257. Binary Tree Paths
- Construct String from Binary TreeStruct
- 226-Invert Binary Tree
- [LintCode] Binary Tree Level Order
- PAT乙級——1093(字串匹配)Java實現字串匹配Java