1115 Counting Nodes in a BST

本文详细介绍了如何使用C++构建二叉树,并实现后序遍历与层级遍历,通过实例展示了如何获取二叉树的高度以及特定层级的节点数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct Node{
	int data,height;
	Node* left;
	Node* right;
};
int n;
vector<int> a,_pos,last,sec;
void insert(Node* &root,int a){
	if(root==NULL){
		root=new Node;
		root->data=a;
		root->left=NULL;
		root->right=NULL;
		return;
	}
	if(a<=root->data) insert(root->left,a);
	else insert(root->right,a);
	
}
Node* build(){
	Node* root=new Node;
	root->data=a[0];
	root->left=NULL;
	root->right=NULL;
	for(int i=1;i<n;i++){
		insert(root,a[i]);
	}
	return root;
}
void pos(Node* root){
	if(root==NULL) return;
	pos(root->left);
	pos(root->right);
	_pos.push_back(root->data);
}
int getheight(Node* root){
	if(root==NULL) return 0;
	return max(getheight(root->left),getheight(root->right))+1;
}
void levetra(Node* root,int b){
	queue<Node*> q;
	root->height=1;
	q.push(root);
	while(!q.empty()){
		Node* now=q.front();
		q.pop();
		if(now->height==b) last.push_back(now->data);
		if(now->height==(b-1)) sec.push_back(now->data);
		if(now->left!=NULL){
			now->left->height=now->height+1;
			q.push(now->left);
		}
		if(now->right!=NULL){
			now->right->height=now->height+1;
			q.push(now->right);
		}
	}
}
int main(){
	#ifndef ONLINE_JUDGE
	freopen("in.txt","r",stdin);
	#endif
	cin>>n;
	a.resize(n);
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	Node* root=build();
	int h=getheight(root);
	levetra(root,h);
	cout<<last.size()<<" + "<<sec.size()<<" = "<<last.size()+sec.size()<<endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值