Home PAT 1110 Complete Binary Tree
Post
Cancel

PAT 1110 Complete Binary Tree

Link

怎么说呢, 竟然会卡在“读入的不一定是字符从而应该用字符串接收”上. 因为, 可以是多位数啊…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <queue>
using namespace std;
int n,root,maxn,last;
struct node{
    int left=-1,right=-1;
}tree[25];
bool v[25];
void DFS(int x,int index){
    if(index>maxn){
        maxn=index;
        last=x;
    }
    if(tree[x].left!=-1) DFS(tree[x].left,index<<1);
    if(tree[x].right!=-1) DFS(tree[x].right,(index<<1)+1);
}
int main() {
    cin>>n;
    for(int i=0;i<n;++i){
        string a,b;
        cin>>a>>b;
        if(a!="-"){
            tree[i].left=stoi(a);
            v[stoi(a)]=true;
        }
        if(b!="-"){
            tree[i].right=stoi(b);
            v[stoi(b)]=true;
        }
    }
    for(int i=0;i<n;++i)
        if(!v[i]){
            root=i;
            break;
        }
    DFS(root,1);
    if(maxn==n) printf("YES %d\n",last);
    else printf("NO %d\n",root);
    return 0;
}
This post is licensed under CC BY 4.0 by the author.