PAT甲1115 Counting Nodes in a BST

题意

求BST倒数2层的结点个数

本来以为是个简单题,但是WA了数据点5 只拿了29分
发现自己并没有考虑0层,1层的树结构,具体表现在算法中使用了len-3,len-2,其中len=树高+1
修改完毕后
len=1(0层) 输出“0 + 0 = 0”
len=2(1层) 输出“0 + 1 = 1”
依旧WA,将“0 + 1 = 1”改成“1 + 0 = 1” 后顺利AC(好坑…)
是我理解的问题吧吧吧

源码

#include<iostream>
#include<queue>
#include<vector> 
using namespace std;
int n;
struct Node{
	int val;
	Node* lchild;
	Node* rchild;
	Node(int x){
		val=x;
		lchild=rchild=NULL;
	}
};
void insertNode(Node* &root,int x){	
	if(root==NULL){
		root=new Node(x);
		return;
	}else{
		if(root->val<x){
			insertNode(root->rchild,x);
		}else{
			insertNode(root->lchild,x);
		}
	}
}
void levelOrder(Node* root){
	queue<Node*>Q;
	Q.push(root);
	int cur=1,next=0;
	vector<int>num;
	num.push_back(cur);
	while(!Q.empty()){
		while(cur--){
			Node* temp=Q.front();
			Q.pop();
			if(temp->lchild){
				Q.push(temp->lchild);
				next++;
			}
			if(temp->rchild){
				Q.push(temp->rchild);
				next++;
			} 
		}
		num.push_back(next);
		cur=next;
		next=0;
	}
	int len=num.size();
	if(len>=3){
		cout<<num[len-2]<<" + "<<num[len-3]<<" = "<<num[len-3]+num[len-2]<<endl;
	}else if(len==1){
		cout<<"0 + 0 = 0"<<endl;
	}else if(len==2){
		cout<<"1 + 0 = 1"<<endl;
	}
}
int main(){
	
	cin>>n;
	Node* root=NULL;
	if(n==0){
		cout<<"0 + 0 = 0"<<endl;
		return 0;
	}
	for(int i=0;i<n;i++){
		int temp;
		cin>>temp;
		insertNode(root,temp);
	}
	levelOrder(root);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值