nyoj498子节点计数

子节点计数

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 4
描述
    给定一棵树的前序和中序序列,求以指定关键字节点为根的子树的节点个数。
输入
第一行包含一个整数 T(T <= 20),表示有几组测试数据;
每组测试数据第一行为整数 N( 1 <= N <= 50),表示树的总结点数;接下来两行为前序和中序序列;第三行有正整数 M( 1 <= M <= 30),表示有 M 条查询; 最后 M 行有 M个整数,表示查询以该整数为关键字的节点。
输入保证前序和中序序列合法且任意两个节点关键字不同。
输出
每组测试数据有 M 行,每行有一个整数表示每条查询的节点总数。
样例输入
1
5
23 2 67 59 98
2 23 59 67 98
4
23
2
67
59
样例输出
5
1
3
1
ac代码:
#include<iterator>
#include<fstream>
#include<string>
#include<set>
#include<vector>
#include<iostream>
#include<cstring>
#include<math.h>
#include<algorithm>
#include<stack>
#include<cstdio>
#include<list>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
using namespace std;
int pre[51];
int in[51];
typedef struct tnode
{
    int data;
    struct tnode* lchild;
    struct tnode* rchild;
}*bt;
void creat(int pre1,int in1,int n,bt &b)
{
    int p;
    int k;
    if(n<=0)
    {
        b=NULL;
        return;
    }
    b=(bt)malloc(sizeof(struct tnode));
    b->data=pre[pre1];
    for(p=in1; p<in1+n; p++)
    {
        if(pre[pre1]==in[p])
        {
            break;
        }
    }
    k=p-in1;
    creat(pre1+1,in1,k,b->lchild);
    creat(pre1+k+1,p+1,n-k-1,b->rchild);
}
int sum;
void pre_vis(bt b)
{
    if(b!=NULL)
    {
        sum++;
        pre_vis(b->lchild);
        pre_vis(b->rchild);
    }
}
void findbt(bt &b,int x)
{
    if(b==NULL)
    {
        return ;
    }
    if(b->data==x)
    {
        pre_vis(b);
        return;
    }
    else
    {
        findbt(b->lchild,x);
        findbt(b->rchild,x);
    }
}
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        int len;
        cin>>len;
        for(int i=0; i<len; i++)
        {
            scanf("%d",&pre[i]);
        }
        for(int i=0; i<len; i++)
        {
            scanf("%d",&in[i]);
        }
        bt t;
        creat(0,0,len,t);
        int m;
        scanf("%d",&m);
        for(int i=0; i<m; i++)
        {
            int x;
            scanf("%d",&x);
            sum=0;
            findbt(t,x);
            cout<<sum<<endl;
        }
    }
}

子节点计数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值