原题链接:1115 Counting Nodes in a BST (30 分)
题目大意:
这个题中的BST
和之前的BST
的定义有点不一样,所以要看清楚题目的条件。
本题将一系列数字按顺序插入到一个空的二叉搜索树中,然后,请你计算结果树的最低两层的结点个数。
分析:
建树 -> DFS,在 DFS
的过程中记录每一层的结点个数和最深的结点。
满分代码:
#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;
const int MAXN = 1e3+10;
int l[MAXN], r[MAXN], v[MAXN], idx, n;
int max_depth, cnt[MAXN];
// 模拟BST的建树过程
void insert(int &u, int w) {
if(!u) {
u = ++idx;
v[u] = w;
// cout << u << endl;
}
else if(w <= v[u]) insert(l[u], w);
else insert(r[u], w);
}
void dfs(int u, int deepth) {
if(u == 0) return;
cnt[deepth]++;
max_depth = max(deepth, max_depth);
dfs(l[u], deepth + 1);
dfs(r[u], deepth + 1);
}
int main() {
cin >> n;
int root = 0;
for(int i = 0; i < n; i++) {
int w;
cin >> w;
insert(root, w);
}
dfs(root, 0);
printf("%d + %d = %d\n", cnt[max_depth], cnt[max_depth - 1], cnt[max_depth] + cnt[max_depth - 1]);
return 0;
}