A1115
Description:
给出BST的插入序列,求最底两层节点个数;
思路:
- 一开始很蠢地将序列排序,然后求二分查找次数以计算深度,竟然没意识到不同的插入顺序将影响树结构…下次注意算法正确性;
- 正确的做法就是:建树、深搜求深度,结束
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;
struct node{
int v;
struct node *l, *r;
};
node* build(node *root , int t){
if(root == nullptr){
root = new node();
root->v = t;
root->l = root->r = nullptr;
}else if(t <= root->v)
root->l = build(root->l, t);
else
root->r = build(root->r, t);
return root;
}
vector<int> num(1000);
int maxlevel = -1;
void dfs(node* root, int level){
if(root == nullptr){
maxlevel = max(level, maxlevel);
return ;
}
num[level]++;
dfs(root->l, level+1);
dfs(root->r, level+1);
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
int n, t;
scanf("%d", &n);
node* root = nullptr;
for(int i = 1; i <= n; i++){
scanf("%d", &t);
root = build(root, t);
}
dfs(root, 0);
printf("%d + %d = %d\n", num[maxlevel-1], num[maxlevel-2], num[maxlevel-1]+num[maxlevel-2]);
return 0;
}