【PAT】1110. Complete Binary Tree

35 篇文章 2 订阅
15 篇文章 0 订阅

考查点:二叉树,完全二叉树,DFS

思路及提交情况:第一次输入接受字符时没考虑getchar接受换行,第二次完全二叉树下标没有从1开始,最后ans记录二叉树节点的数组n-1没有修改为n,完全改好后一直段错误实际上是程序错误,就是接收数据时出错了,只接受字符,所以节点是二位数时输入就会溢出出现段错误,以后段错误要记得可能是输入有问题,还有不要理所当然从样例看出一定是接收字符,有可能是两位数。

#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#define FOR(i, x, y) for(int i = x; i <= y; i++)
#define rFOR(i, x, y) for(int i = x; i >= y; i--)
#define MAXN 10010
#define oo 0x3f3f3f3f
using namespace std;
const int N=40;
int lch[N];
int rch[N];
int n;
void DFS(int root,int& num)
{
    if(root==-1 || num==n)return ;
    num++;
    DFS(lch[root],num);
    DFS(rch[root],num);

}
int cnt=1;
int ans[100];
int isroot[N];
int findroot()
{
    for(int i=0;i<n;i++)
        if(isroot[i]==0)return i;
}
void DDFS(int root,int cnt)
{
    if(root==-1||cnt==n+1)return ;
    ans[cnt]=root;
    DDFS(lch[root],cnt*2);
    DDFS(rch[root],cnt*2+1);

}
int change(char str[])
{
    int i=0;
    int res=0;
    int len=strlen(str);
    while(i<len)
    {
        res=res*10+str[i]-'0';i++;
    }
    return res;
}

void BFS(int root)
{
    queue<int> q;
    q.push(root);

    while(!q.empty())
    {
        int id=q.front();
        ans[cnt++]=id;
        q.pop();
        if(lch[id]!=-1){
            q.push(lch[id]);

        }
        if(rch[id]!=-1){
            q.push(rch[id]);
        }
    }
}

int main()
{
     #ifdef LOCAL
        freopen("data.in","r",stdin);
        freopen("data.out","w",stdout);
    #endif // LOCAL
    char s1[5],s2[5];
    scanf("%d",&n);

    FOR(i,0,n-1)
    {
        scanf("%s%s",s1,s2);
        if(s1[0]!='-'){
            int ll=change(s1);
            isroot[ll]=1;
            lch[i]=ll;
        }
        else lch[i]=-1;
        if(s2[0]!='-'){
            int rr=change(s2);
            rch[i]=rr;
            isroot[rr]=1;
        }
        else rch[i]=-1;
       // cout<<s1<<s2<<endl;

    }
    bool ok=false;
    int root=findroot();
    FOR(i,0,40)
    {
        ans[i]=-2;
    }

    DDFS(root,cnt);
   // BFS(root);
    FOR(i,1,n)
    {
       // cout<<ans[i]<<endl;
        if(ans[i]==-2){
            ok=true;

            break;
        }
    }
    if(ok==false){
        printf("YES %d",ans[n]);

    }else{
        printf("NO %d",root);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值