对输入的每个点都进行一插入操作,然后得出最深的那一层,然后进行广度优先搜索进行计算最后两层的结点的数量。
AC代码:
#include<iostream>
#include<map>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<set>
#include<stack>
#include<cmath>
#include<vector>
#include<hash_map>
#define ll long long
#define inf 24*60*60
using namespace std;
struct node
{
int data;
int lay;
node* l=NULL;
node* r=NULL;
};
int maxx=-1;
void in(node* & dian,int data,int lay)
{
if(lay>maxx)
{
maxx=lay;
}
if(dian==NULL)
{
dian=new node;
dian->data=data;
dian->lay=lay;
}
else
{
if(data<=dian->data)
{
in(dian->l,data,lay+1);
}
else
{
in(dian->r,data,lay+1);
}
}
}
int ans1=0;
int ans2=0;
void bfs(node* dian)
{
queue<node> q;
q.push(*dian);
while(!q.empty())
{
node tmp=q.front();
q.pop();
if(tmp.lay==maxx-1)
{
ans1++;
}
if(tmp.lay==maxx)
{
ans2++;
}
if(tmp.l!=NULL)
{
q.push(*tmp.l);
}
if(tmp.r!=NULL)
{
q.push(*tmp.r);
}
}
}
int main()
{
int n;
scanf("%d",&n);
node* root=NULL;
for(int i=0;i<n;i++)
{
int d;
scanf("%d",&d);
in(root,d,0);
}
bfs(root);
printf("%d + %d = %d",ans2,ans1,ans1+ans2);
}