思路:
1.用指针建树,因为树中有重复元素,所以不可以用映射;
2.建树时记录每个结点的level,在new node()时,相应的mp[level]加一;
3.用逆序的map,最后输出第一个元素和第二个元素和它们的和就好了;
代码:
#include<iostream>
#include<map>
using namespace std;
struct node{
int val;
node *left,*right;
};
map<int,int,greater<int>> mp;
node* insert(node *p,int val,int level){
if(p==NULL){
p=new node();
p->val=val;
mp[level]++;
return p;
}
if(val<=p->val) p->left=insert(p->left,val,level+1);
else p->right=insert(p->right,val,level+1);
return p;
}
int main(){
int n,val;
scanf("%d",&n);
node *root=NULL;
for(int i=0;i<n;i++){
scanf("%d",&val);
root=insert(root,val,1);
}
map<int,int,greater<int>>::iterator it=mp.begin();
int a=it->second;
it++;
int b=it->second;
printf("%d + %d = %d",a,b,a+b);
return 0;
}