0
点赞
收藏
分享

微信扫一扫

PAT_甲级_1115 Counting Nodes in a BST (30分) (C++)【签到题/指针构建BST】


目录

​​1,题目描述​​

​​ 题目大意​​

​​2,思路​​

​​3,AC代码​​

​​4,解题过程​​

​​第一搏​​

​​第二搏​​

1,题目描述

PAT_甲级_1115 Counting Nodes in a BST (30分) (C++)【签到题/指针构建BST】_指针构建BST

Sample Input:

9
25 30 42 16 20 20 35 -5 28

 

Sample Output:

2 + 4 = 6

 题目大意

根据输入序列,构建BST(不需要保持平衡或是其他什么条件,简直不要太简单)。并输出后两层节点数目之和;

 

2,思路

利用指针构建BST树,同时记录树的最大高度,和每层高度的节点数目;

PAT_甲级_1115 Counting Nodes in a BST (30分) (C++)【签到题/指针构建BST】_1115_02

直接输出

PAT_甲级_1115 Counting Nodes in a BST (30分) (C++)【签到题/指针构建BST】_指针构建BST_03

3,AC代码

#include<bits/stdc++.h>
using namespace std;
int maxDep = 0, record[1005];
struct node{
int key;
node* left = NULL;
node* right = NULL;
};
void add(node*& root, int key, int dep){ // !!!node*& root
if(root == NULL){
root = new node();// !!!
root->key = key;
record[dep]++;
maxDep = max(maxDep, dep);
return;
}
if(root->key < key)
add(root->right, key, dep+1);
else
add(root->left, key, dep+1);
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
int N, num;
cin>>N;
node* tree = NULL;// !!!
fill(record, record + 1005, 0);
for(int i = 0; i < N; i++){
cin>>num;
add(tree, num, 1);
}
printf("%d + %d = %d", record[maxDep], record[maxDep-1], record[maxDep] + record[maxDep-1]);
delete(tree);
return 0;
}

4,解题过程

第一搏

这是30分的题。。。

我一顿操作下来

#include<bits/stdc++.h>
using namespace std;
int maxDep = 0, record[1005];
struct node{
int key;
node* left = NULL;
node* right = NULL;
};
void add(node*& root, int key, int dep){ // !!!node*& root
if(root == NULL){
root = new node();// !!!
root->key = key;
record[dep]++;
maxDep = max(maxDep, dep);
return;
}
if(root->key <= key)
add(root->right, key, dep+1);
else
add(root->left, key, dep+1);
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
int N, num;
cin>>N;
node* tree = NULL;// !!!
for(int i = 0; i < N; i++){
cin>>num;
add(tree, num, 1);
}
printf("%d + %d = %d", record[maxDep], record[maxDep-1], record[maxDep] + record[maxDep-1]);
delete(tree);
return 0;
}

PAT_甲级_1115 Counting Nodes in a BST (30分) (C++)【签到题/指针构建BST】_C++_04

第二搏

不会这么惨吧,,,这样的题也能(;′⌒`)

我又重新扫了一遍题目,发现

PAT_甲级_1115 Counting Nodes in a BST (30分) (C++)【签到题/指针构建BST】_1115_05

吐了,前面的题目关于BST的都是等于的放在右边了,这里却是放在左边。。。

PAT_甲级_1115 Counting Nodes in a BST (30分) (C++)【签到题/指针构建BST】_C++_06

举报

相关推荐

0 条评论