L2-3 二叉搜索树的2层结点统计 (25 分)

L2-3 二叉搜索树的2层结点统计 (25 分)

二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树:若它的左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值;若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉搜索树。
将一系列数字按给定顺序插入一棵初始为空的二叉搜索树,你的任务是统计结果树中最下面 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<iostream>
#include<queue>

using namespace std;

int maxH = 0;
//int count = 0;
struct Node{ //树节点
    int data;
    int height;
    Node* Ltree;
    Node* Rtree;
};
void Insert(Node* tree,int num,int h){  //根据数组顺序插入数据
    //int height = 0;
    if(num>tree->data){
        if(tree->Rtree==NULL){
            tree->Rtree = new Node;
            tree->Rtree->data = num;
            tree->Rtree->Ltree = NULL;
            tree->Rtree->Rtree = NULL;
            tree->Rtree->height = h;
        }
        else{
            //cout << "left";
            Insert(tree->Rtree,num,h+1);
            
        }
    }
    else{
        if(tree->Ltree==NULL){
            tree->Ltree = new Node;
            tree->Ltree->data = num;
            tree->Ltree->Ltree = NULL;
            tree->Ltree->Rtree = NULL;
            tree->Ltree->height = h;
        }
        else{
            //cout << "right";
            Insert(tree->Ltree,num,h+1);  //每次插入深度加一
        }
    }
}
int layerorder(Node* root)  //层次遍历得到树的深度
{
	queue<Node*> q;
	q.push(root);
	while(!q.empty())
	{
		Node* now = q.front();
		q.pop();
        if(now->height>maxH){
            maxH = now->height;
        }
		if(now->Ltree != NULL) q.push(now->Ltree);
		if(now->Rtree != NULL) q.push(now->Rtree);
	}
    return maxH;
}
int returnCount(Node* root)  //还是层次遍历,得到最后两层的所有节点
{
    int count = 0;
	queue<Node*> q;
	q.push(root);
	while(!q.empty())
	{
		Node* now = q.front();
		q.pop();
        if(now->height==maxH||now->height==maxH-1){
            count++;
        }
		if(now->Ltree != NULL) q.push(now->Ltree);
		if(now->Rtree != NULL) q.push(now->Rtree);
	}
    return count;
}
int main(){
    int n;
    int num;
    cin >> n;
    Node* root = new Node;
    cin >> num;   //先把第一个数插进去
    root->data = num;
    root->Ltree = NULL;
    root->Rtree = NULL;
    root->height = 0;
    for(int i=1;i<n;i++){
        cin >> num;
        Insert(root,num,1);
    }
    maxH = layerorder(root);
    cout << returnCount(root);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值