1115 Counting Nodes in a BST

98 篇文章 0 订阅
21 篇文章 0 订阅

在这里插入图片描述在这里插入图片描述

题目大意:

数一个BST(二叉查找树)最后两层节点的数量。

解题思路:

维护一个深度参数,建树时记录下最大深度然后BFS遍历统计即可。
代码如下:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
using namespace std;
int n,ma=0,n1,n2;
struct node
{
	node* lchild;
	node* rchild;
	int data,depath=0;
};
node* newnode(int data)
{
	node* tmp=new node;
	tmp->lchild=NULL;
	tmp->rchild=NULL;
	tmp->data=data;
	return tmp;
}
void create(node* &root,int data,int level)
{
	if(root==NULL)
	{
	  root=newnode(data);
	  root->depath=level+1;
	  if(root->depath>ma)ma=root->depath;
	  return;	
	}
	if(data>root->data)create(root->rchild,data,root->depath);
	else create(root->lchild,data,root->depath);
}
void bfs(node* root)
{
	queue<node*> q;
	q.push(root);
	while(!q.empty())
	{
		node* tmp=q.front();
		q.pop();
		if(tmp->depath==ma)n1++;//如果是最后一层 
		else if(tmp->depath==(ma-1))n2++;//如果是倒数第二层 
		if(tmp->lchild!=NULL)q.push(tmp->lchild);
		if(tmp->rchild!=NULL)q.push(tmp->rchild);
	}
}
int main()
{
	scanf("%d",&n);
	node* root=NULL;
	for(int i=0;i<n;i++)
	{
		int tmp;
		scanf("%d",&tmp);
	    create(root,tmp,0);
    }
	bfs(root);
	printf("%d + %d = %d\n",n1,n2,n1+n2);
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值