1115 Counting Nodes in a BST (30 分)

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

AC代码:

一开始考虑错n1,n2的值,结果只得了2分,而后看大佬代码,发现问题。

我用的是层次遍历,先给每层结点赋上层次值,然后再先序遍历,记录n1与n2,然后给出答案,

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;

const int maxn = 1010;
struct node {
	int data;
	node* lchild;
	node* rchild;
	int layer;
};
node* newNode(int val) {
	node* Node = new node;
	Node->data = val;
	Node->lchild = Node->rchild = NULL;
	return Node;
}

void insert(node* &root, int x) {
	if (root == NULL) {
		root = newNode(x);
		return;
	}
	if (x == root->data) {
		insert(root->lchild, x);
	}
	else if (x < root->data) {
		insert(root->lchild, x);
	}
	else {
		insert(root->rchild, x);
	}
}

int max_layer = 1, n1, n2;
void LayerOrder(node* root) {
	queue<node*> q;
	root->layer = 1;
	q.push(root);
	while (!q.empty()) {
		node* now = q.front();
		q.pop();
		max_layer = max(max_layer, now->layer);
		if (now->lchild != NULL) {
			now->lchild->layer = now->layer + 1;
			q.push(now->lchild);
		}
		if (now->rchild != NULL) {
			now->rchild->layer = now->layer + 1;
			q.push(now->rchild);
		}
	}
}

void preOrder(node* root) {
	if (root == NULL)
		return;
	if (root->layer == max_layer )
		n1++;
	if (root->layer == max_layer - 1)
		n2++;
	preOrder(root->lchild);
	preOrder(root->rchild);
}

int main() {
	int n, data;
	node* root = NULL;
	scanf_s("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf_s("%d", &data);
		insert(root, data);
	}
	LayerOrder(root);
	preOrder(root);
	printf("%d + %d = %d", n1, n2, n1 + n2);
	
	return 0;
}

大家的方案都是用DFS,

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;

const int maxn = 1010;
struct node {
	int data;
	node* lchild;
	node* rchild;
///	int layer;
};
node* newNode(int val) {
	node* Node = new node;
	Node->data = val;
	Node->lchild = Node->rchild = NULL;
	return Node;
}


void insert(node* &root, int x) {
	if (root == NULL) {
		root = newNode(x);
		return;
	}
	if (x == root->data) {
		insert(root->lchild, x);
	}
	else if (x < root->data) {
		insert(root->lchild, x);
	}
	else {
		insert(root->rchild, x);
	}
}

int maxdepth = -1;
vector<int> v(1010);
void dfs(node* root, int h) {
	if (root == NULL)
		return;
	maxdepth = max(h, maxdepth);
	v[h]++;
	dfs(root->lchild, h + 1);
	dfs(root->rchild, h + 1);
	return;
}
int main() {
	int n, x;
	node* root = NULL;
	scanf_s("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf_s("%d", &x);
		insert(root, x);
	}
	dfs(root, 0);
	printf("%d + %d = %d", v[maxdepth], v[maxdepth - 1], v[maxdepth] + v[maxdepth - 1]);
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值