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, or NO
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
-
思路 1:类似于:已知树形(完全二叉树:
id :左 2*id, 右 2*id+1
)+ 一个遍历序列 =》 得到树 的问题
静态存储树后先序遍历,将节点存入一个数组(将下标作为参数传入PreOrder() )
遍历数组判断是否前n个元素都装满 -
TIPS:节点编号从0开始连续:求根
可以先求出0 + 1 + 2 + … + n-1 = (n - 1) * n / 2 并减去空指针(-1)
然后每得到一个孩子节点的编号就减去这个编号(因为空指针为-1,已经处理过,不用单独考虑) -
code :
#include <bits/stdc++.h>
using namespace std;
const int maxn = 50;
bool not_root[maxn];
struct Node{
int lc, rc;
}node[maxn];
int GetRoot(int n){
for(int i = 0; i < n; ++i) if(not_root[i] == false) return i;
}
int tree[maxn];
void PreOrder(int r, int id){
if(r == -1) return;
tree[id] = r;
PreOrder(node[r].lc, 2 * id);
PreOrder(node[r].rc, 2 * id + 1);
}
int main(){
int n;
scanf("%d", &n);
int r = (n - 1) * n / 2 - (n + 1); //所有节点编号和-空指针数
for(int i = 0; i < n; ++i){
getchar();
string tl, tr;
cin >> tl >> tr;
node[i].lc = tl[0] == '-' ? -1 : stoi(tl);
node[i].rc = tr[0] == '-' ? -1 : stoi(tr);
r -= (node[i].lc + node[i].rc);
}
memset(tree, -1, sizeof(tree));
PreOrder(r, 1);
for(int i = 1; i <= n; ++i){
if(tree[i] == -1){
printf("NO %d", r);
return 0;
}
}
printf("YES %d", tree[n]);
return 0;
}
- T3 code:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 110;
struct Node
{
int data, lc, rc;
}node[maxn];
int Change(char s[])
{
return s[0] == '-' ? -1 : atoi(s);
}
void PreOrder(int id, int root, int n, int & end_node, bool & flg)
{
if(root == -1 || flg == false) return;
PreOrder(id * 2, node[root].lc, n, end_node, flg);
if(id > n)
{
flg = false;
return;
}
if(id == n) end_node = root;
PreOrder(id * 2 + 1, node[root].rc, n, end_node, flg);
}
int main()
{
int n;
scanf("%d", &n);
int r = (n - 1) * n / 2 - (n + 1);
for(int i = 0; i < n; ++i)
{
char lc[5], rc[5];
scanf("%s %s", lc, rc);
node[i].lc = Change(lc);
node[i].rc = Change(rc);
r -= (node[i].lc + node[i].rc);
}
bool flg = true;
int end_node;
PreOrder(1, r, n, end_node, flg);
if(flg == false)
{
printf("NO %d", r);
}else
{
printf("YES %d", end_node);
}
return 0;
}