7-4 Structure of a Binary Tree (30 分)

本文介绍了一种通过后序遍历和中序遍历构建二叉树的方法,并实现了一个判断系统,用于解析和验证关于树结构的特定条件语句。通过递归方式构建树结构,并针对不同类型的判断语句(如根节点、兄弟节点、父节点等)进行有效性检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:根据后序和中序,然后给定一些判断语句,判断该语句是否正确。

解题思路:首先是建树,然后判断语句。如何来输入语句和读懂语句意思?一个一个单词的读。然后判断关键词。返回问题的句意,并得到A、B的值,然后判断。

AC代码:

#include<iostream>
#include<vector>
#include<cstdio>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
#define MAX 40
struct node{
    int l,r,d,p;
    node(){}
    node(int l,int r,int d,int p):l(l),r(r),d(d),p(p){}
};
map<int,node>arr;
int po[MAX],in[MAX],N,A,B;
bool flag=0;
string str;
int tree(int poR,int inL,int inR,int de,int pa)
{
    if(inL>inR)return -1;
    int i=inL;
    while(in[i]!=po[poR])++i;
    arr[po[poR]].p=pa;
    arr[po[poR]].d=de;
    arr[po[poR]].l=tree(poR-(inR-i)-1,inL,i-1,de+1,po[poR]);
    arr[po[poR]].r=tree(poR-1,i+1,inR,de+1,po[poR]);
    if((arr[po[poR]].r==-1&&arr[po[poR]].l!=-1)||(arr[po[poR]].r!=-1&&arr[po[poR]].l==-1))flag=1;
    return po[poR];
}
int input()
{
    int i;
    cin>>str;
    if(str[0]>='0'&&str[0]<='9'){
        i=0;A=0;
        while(i<str.length()){A=A*10+str[i]-'0';++i;}
        cin>>str;
        if(str=="and"){
            scanf("%d",&B);
            cin>>str;cin>>str;
            if(str=="siblings"){
                return 2;
            }else{
                i=3;
                while(i--){cin>>str;}
                return 6;
            }
        }else{
            cin>>str;cin>>str;
            if(str=="root")return 1;
            else if(str=="parent"){
                cin>>str;scanf("%d",&B);
                return 3;
            }else if(str=="left"){
                cin>>str;cin>>str;scanf("%d",&B);
                return 4;
            }else if(str=="right"){
                cin>>str;cin>>str;scanf("%d",&B);
                return 5;
            }
        }
    }else{
        i=4;
        while(i--)cin>>str;
        return 7;
    }
}
int main()
{
    //freopen("test.txt","r",stdin);
    scanf("%d",&N);
    for(int i=0;i<N;++i)scanf("%d",&po[i]);
    for(int i=0;i<N;++i)scanf("%d",&in[i]);
    int root=tree(N-1,0,N-1,0,-1);
    scanf("%d",&N);
    while(N--){
        int x=input();
        bool f=0;
        if(x==1){
            if(A!=root)f=1;
        }else if(x==2){
            if(arr[A].p!=arr[B].p)f=1;
        }else if(x==3){
            if(arr[B].p!=A)f=1;
        }else if(x==4){
            if(arr[B].l!=A)f=1;
        }else if(x==5){
            if(arr[B].r!=A)f=1;
        }else if(x==6){
            if(arr[B].d!=arr[A].d)f=1;
        }else if(x==7){
            if(flag)f=1;
        }
        if(f)printf("No\n");
        else printf("Yes\n");
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值