二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树:若它的左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值;若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉搜索树。
将一系列数字按给定顺序插入一棵初始为空的二叉搜索树,你的任务是统计结果树中最下面 2 层的结点数。
输入格式:输入在第一行给出一个正整数 N (≤1000),为插入数字的个数。第二行给出 N 个 [−1000,1000] 区间内的整数。数字间以空格分隔。
输出格式:在一行中输出最下面 2 层的结点总数。
输入样例:9
25 30 42 16 20 20 35 -5 28
输出样例:6
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <bits/stdc++.h>
using namespace std;
typedef struct Node {
int val;
Node* left;
Node* right;
int size; //子树数量
int tall;//高度
}node, *pNode;
int max1 = 0;
int daan = 0;
//创建二叉搜索树
pNode buildTree(pNode &tree, int num,int tall){
if(tree == NULL){
tree = new node; //开辟空间
tree->val = num; //赋值
tree->left = tree->right = NULL;
tree->tall = tall;//深度
if(tall > max1){ //记录最大深度
max1 = tall;
}
//cout << "22" << ' ' << tree->val <<endl;
return tree;
}
//用二层搜索树的性质递归插入结点
if(num <= tree->val){
tree->left = buildTree(tree->left, num, tall+1);
}
else {
tree->right = buildTree(tree->right, num, tall+1);
}
return tree;
}
//中序遍历
void inOrder(pNode &root){
if(root == NULL)
return;
inOrder(root->left);
if(root->tall >= max1-1){ //如果是最下两层,答案daan+1
daan++;
}
inOrder(root->right);
}
int main(){
int n;
cin >> n;
int num;
node *root = NULL;
for(int i = 0; i < n; i++){
cin >> num;
buildTree(root, num, 1);
}
//cout << max1 << endl;
inOrder(root);
cout << daan;
return 0;
}