这个题目算是30分大题里面比较简单的了,按照常规套路构造BST,不过可以在节点的定义中加上深度这个成员变量,在构造BST的过程中把每个成员的深度记录下来,并记录好最大深度以及每个深度的节点数目,最后直接按题意输出即可。
#include<bits/stdc++.h>
using namespace std;
struct Node{
int v, depth;
Node* lchild, *rchild;
};
Node* root = NULL;
int maxdps = -1;
int ans[1005] = {0};
void Insert(Node* &rt, int x, int dps){
if(rt == NULL){
Node* newnode = new Node;
newnode->v = x;
newnode->depth = dps;
newnode->lchild = newnode->rchild = NULL;
rt = newnode;
ans[dps]++;
if(maxdps < dps) maxdps = dps;
return;
}
if(x <= rt->v) Insert(rt->lchild, x, dps+1);
else Insert(rt->rchild, x, dps+1);
return;
}
int main(){
int n, x;
cin >> n;
for(int i=0; i<n; i++){
cin >> x;
Insert(root, x, 1);
}
printf("%d + %d = %d",ans[maxdps], ans[maxdps-1], ans[maxdps] + ans[maxdps-1]);
}