版权声明:如若转载,请联系作者。 https://blog.csdn.net/liu16659/article/details/89608656
1115 Counting Nodes in a BST C++版
1.题意
给出一串数字,让你建成一个二叉搜索树,同时,你需要给出最终的二叉搜索树的最后一层和倒数第二层的结点数。
2.分析
分成如下两步实现即可:
- step 1:建一棵二叉搜索树
- step 2: 使用某种遍历,将节点层数及节点的值放入到vector中
- step 3:记录该树中最大的层maxFloor,然后输出maxFloor层以及maxFloor-1层的节点数即可
3.代码
#include<cstdio>
#include<iostream>
#include<vector>
#define maxn 1005
using namespace std;
struct node{
int data;
node *left,*right;
int height;//该层的高度
};
vector<int> res[maxn];//遍历的结果
int n1,n2;//表示最后一层,倒数第二层的节点数
int maxFloor = 0;//表示最大层
//往二叉树中插入一个值
void insert(node* &root,int data,int height){
if(root == NULL){//到达了空节点, 即为需要插入的位置
root = new node;
root->data = data;//赋值
root->height = height;
root->left = root->right = NULL;//均为NULL
return;
}
if(data <= root->data) insert(root->left,data,++height);//插入到左子树中 ,注意这里有=号
else insert(root->right,data,++height);//插入到右子树中
}
void inOrder(node* root){
if(root == NULL) return;//到达空树,返回
inOrder(root->left);
res[root->height].push_back(root->data);
if(root->height > maxFloor){
maxFloor = root->height;//更新maxFloor的值
}
inOrder(root->right);
}
int main(){
int n,data;
node* root = NULL;//定义头结点 ,初始为null
scanf("%d",&n);
for(int i = 0;i< n;i++){
scanf("%d",&data);
insert(root,data,0);
}
inOrder(root);
n1 = res[maxFloor].size();
n2 = res[maxFloor-1].size();
cout << n1 <<" + "<< n2 <<" = "<< n1+n2 <<"\n";
}
4.测试用例
9
25 30 42 16 20 20 35 -5 28
9
25 30 42 16 20 42 35 -5 28
3
1 2 3