PAT——1115 Counting Nodes in a BST 甲级(dfs和bfs均可)

这篇博客介绍了如何在二叉搜索树中插入元素并进行层次遍历,以计算最低两层节点的数量及其总和。提供了AC代码实现,包括使用BFS的方法。此外,还给出了DFS的参考代码,帮助理解不同遍历方式。

1115 Counting Nodes in a BST

题目

https://pintia.cn/problem-sets/994805342720868352/problems/994805355987451904

题意

将给定数字放入二叉搜索树中,并输出最低两层的结点数量及其总和

代码解析

建树的insert函数就是常规流程

判断结点数有两种方式——dfs和bfs,这两个方法都能AC

AC代码

#include<bits/stdc++.h>
using namespace std;
typedef struct node* tree;
struct node{
	int data;
	tree left,right;
};
tree insert(tree a,int t)
{
	if(!a)
	{
		a=new node();
		a->data=t;
		a->left=a->right=NULL;
		return a;
	}
	else if(t<=a->data)
		a->left=insert(a->left,t);
	else
		a->right=insert(a->right,t);
	return a;
}
vector<int> ans(1005,0);
int pos=0;
void bfs(tree a)
{
	queue<tree> q;
	q.push(a);
	tree last=q.back();
	while(q.size())
	{
		tree b=q.front();
		q.pop();
		ans[pos]++;
		if(b->left) q.push(b->left);
		if(b->right) q.push(b->right);
		if(b==last) 
		{
			pos++;
			last=q.back();
		}
	}
}
//void dfs(tree a,int depth)
//{
//	if(a==NULL)
//	{
//		pos=max(pos,depth);
//		return;
//	}
//	ans[depth]++;
//	dfs(a->left,depth+1);
//	dfs(a->right,depth+1);
//}
int main()
{
	int n,t;
	tree a=NULL;
	cin>>n;
	while(n--)
	{
		cin>>t;
		a=insert(a,t);
	}
	bfs(a);
//	dfs(a,0);
	int x=ans[pos-1],y=ans[pos-2];
	printf("%d + %d = %d",x,y,x+y);
}

参考

dfs部分参考了1115. Counting Nodes in a BST (30)-PAT甲级真题(二叉树的遍历,dfs)

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值