题目大意

主要思路
由于二叉搜索树是左子树上所有结点的值均小于或等于它的根结点的值,右子树上所有结点的值均大于它的根结点的值,所以我们每插入一个点就要从根节点dfs找到能存放该点的地方,也就是说如果这个值大于根节点就要往右找,小于等于根节点就要往左找,递归此过程,这样建树并且更新最大深度
AC代码
代码通俗易懂
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <string>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
#include <sstream>
using namespace std;
const int N = 1010, INF = 0x3f3f3f3f;
int n, l[N], r[N], pos[N];
int cnt[N], max_depth;
void dfs(int root, int u, int depth)
{
if(pos[u] <= pos[root])
{
if(l[root] == INF)
{
l[root] = u;
cnt[depth+1]++;
max_depth = max(max_depth, depth+1);
return ;
}
else
{
dfs(l[root], u, depth + 1);
return ;
}
}
else
{
if(r[root] == INF)
{
r[root] = u;
cnt[depth + 1]++;
max_depth = max(max_depth, depth + 1);
return ;
}
else
{
dfs(r[root], u, depth + 1);
return ;
}
}
}
int main(void)
{
memset(l, 0x3f, sizeof(l));
memset(r, 0x3f, sizeof(r));
cin >> n;
if(n == 1)
{
cout << 1 << endl;
return 0;
}
for(int i = 0; i < n; i++)
{
int x;
cin >> x;
if(!i)
{
pos[i] = x;
}
else
{
pos[i] = x;
dfs(0, i, 0);
}
}
cout << cnt[max_depth] + cnt[max_depth - 1] << endl;
return 0;
}
1493

被折叠的 条评论
为什么被折叠?



