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; }
相关文章推荐
- 1115. Counting Nodes in a BST (30) PAT 甲级
- PAT 1115. Counting Nodes in a BST (30) 建树
- PAT (Advanced Level) Practise 1115 Counting Nodes in a BST (30)
- PAT--1115. Counting Nodes in a BST
- 【PAT】1115. Counting Nodes in a BST
- PAT (Advanced Level) 1115. Counting Nodes in a BST (30) 解题报告
- pat 1115 Counting Nodes in a BST (30)
- pat甲1115. Counting Nodes in a BST(BST二叉搜索树)
- PAT (Advanced Level)1115. Counting Nodes in a BST (30)
- PAT 1115. Counting Nodes in a BST (30) 搜索树建立 + 各层节点数量判断
- PAT甲级 1115. Counting Nodes in a BST (30)
- 【PAT】【Advanced Level】1115. Counting Nodes in a BST (30)
- PAT (Advanced Level) 1115. Counting Nodes in a BST (30)
- PAT 1115 Counting Nodes in a BST (30)
- PAT (Advanced Level)-1115 Counting Nodes in a BST
- pat 1115. Counting Nodes in a BST (30)
- solution Of Pat 1115. Counting Nodes in a BST (30)
- PAT 1115 Counting Nodes in a BST
- PAT甲级 1115. Counting Nodes in a BST
- PAT 甲级 1115. Counting Nodes in a BST (30)