您的位置:首页 > Web前端 > Node.js

PAT甲1115 Counting Nodes in a BST

2019-08-02 15:28 1181 查看

题意

求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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: