题目描述
二叉搜索树(BST)递归定义为具有以下属性的二叉树:
节点的左子树只包含键值小于或等于节点键值的节点。
节点的右子树只包含键值大于节点键值的节点。
左子树和右子树都必须是二叉搜索树。
在初始为空的二叉搜索树中插入一个数字序列。计算树的最低2层中的节点总数。
输入描述:
每个输入包含一个测试用例。对于每种情况,第一行给出一个正整数N(N
≤
≤ 1000),这是输入序列的大小。然后在下一行给出[-1000 1000]中的N个整数,把这些数插入到一个初始为空的二叉搜索树中。
输出描述:
对于每种情况,在一行中打印结果树的最低2层的节点数,格式为
n1 + n2 = n
其中n1为最低层的节点数,n2为上一层的节点数,n为和。
输入数据 1
9
25 30 42 16 20 20 35 -5 28
输出数据 1
2 + 4 = 6
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
if(n==2||n==3)
{
cout<<"是素数";
}
else if(n%6!=1&&n%6!=5)
{
cout<<"不是素数";
}
else
{
for(int i=2;i*i<=n;i++)
{
if(!(n%i))
{
cout<<"不是素数" ;
return 0;
}
}
cout<<"是素数";
}
}
首先,我们需要构建一个二叉搜索树,并插入给定的数字序列。
然后,我们需要计算树的最低2层中的节点总数。
步骤如下:
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
void insertNode(struct TreeNode** root, int val) {
if (*root == NULL) {
*root = malloc(sizeof(struct TreeNode));
(*root)->val = val;
(*root)->left = NULL;
(*root)->right = NULL;
} else {
if (val < (*root)->val) {
insertNode(&((*root)->left), val);
} else {
insertNode(&((*root)->right), val);
}
}
}
int countNodes(struct TreeNode* root) {
if (root == NULL) {
return 0;
}
int countLowest = 0;
int countSecondLowest = 0;
struct TreeNode* queue[1000];
int front = 0;
int rear = 0;
queue[rear++] = root;
while (front < rear) {
int levelSize = rear - front;
int levelCount = 0;
for (int i = 0; i < levelSize; i++) {
struct TreeNode* current = queue[front++];
levelCount++;
if (current->left != NULL) {
queue[rear++] = current->left;
}
if (current->right != NULL) {
queue[rear++] = current->right;
}
}
if (levelCount > 0) {
countLowest = countSecondLowest;
countSecondLowest = levelCount;
}
}
return countLowest + countSecondLowest;
}
int main() {
int n;
scanf("%d", &n);
int nums[1000];
for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
}
struct TreeNode* root = NULL;
for (int i = 0; i < n; i++) {
insertNode(&root, nums[i]);
}
int totalCount = countNodes(root);
int countSecondLowest = totalCount - (root->left == NULL ? 0 : 1) - (root->right == NULL ? 0 : 1);
printf("%d + %d = %d\n", countSecondLowest, totalCount - countSecondLowest, totalCount);
return 0;
}
这样,我们就得到了计算二叉搜索树最低2层的节点总数的完整解决方案。
注意:以上代码为C语言代码,可以在编译器中运行,如果使用其他编程语言,请根据语法特点进行相应的调整。