PAT甲级1115 【Counting Nodes in a BST 】(30)

4 篇文章 0 订阅
2 篇文章 0 订阅

分析:一次AC的感觉真爽,BST的常规题,dfs求出层数,再用bfs遍历。

#include<stdio.h>
#include<queue>
#include<stdlib.h>
using namespace std;

typedef struct BNode{
	int data, layer;
	struct BNode *l, *r;
}BNode, *BTree;

BTree insert(BTree root, int num){
	if(root == NULL){
		root = (BTree)malloc(sizeof (BNode));
		root->data = num;
		root->l = root->r = NULL;
		return root;
	}
	if(num > root->data)
		 root->r = insert(root->r, num);
	else root->l = insert(root->l, num);
	return root;
}
int findD(BTree root){
	if(root == NULL) return 0;
	int l = findD(root->l)+1;
	int r = findD(root->r)+1;
	return l > r ? l : r;
}

void bfs(BTree root){
	int len = findD(root);
	int layer = 1, cnt1 = 0, cnt2 = 0;
	root->layer = 1;
	queue<BTree> q;
	q.push(root);
	while(!q.empty()){
		BTree cur = q.front();
		q.pop();
		if(cur->layer == len-1) cnt2++;
		else if(cur->layer == len) cnt1++;
		if(cur->l) {
			cur->l->layer = cur->layer+1;
			q.push(cur->l);
		}
		if(cur->r){
			cur->r->layer = cur->layer+1;
			q.push(cur->r);
		}
	} 
	printf("%d + %d = %d\n", cnt1, cnt2, cnt1+cnt2);
}
int main(){
//	freopen("in.txt", "r", stdin);
	int n, num, i;
	BTree root = NULL;
	scanf("%d", &n);
	for(i = 0; i<n; i++){
		scanf("%d", &num);
		root = insert(root, num);
	}
	bfs(root);
	
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值