1115 Counting Nodes in a BST (30 point(s))
A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
- The left subtree of a node contains only nodes with keys less than or equal to the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Insert a sequence of numbers into an initially empty binary search tree. Then you are supposed to count the total number of nodes in the lowest 2 levels of the resulting tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤1000) which is the size of the input sequence. Then given in the next line are the N integers in [−10001000] which are supposed to be inserted into an initially empty binary search tree.
Output Specification:
For each case, print in one line the numbers of nodes in the lowest 2 levels of the resulting tree in the format:
n1 + n2 = n
where n1
is the number of nodes in the lowest level, n2
is that of the level above, and n
is the sum.
Sample Input:
9
25 30 42 16 20 20 35 -5 28
Sample Output:
2 + 4 = 6
中规中矩的压轴题。非常开心,25分钟AC本题。
题意:
根据给定的序列生成二叉搜索树,并计算最后两层的结点数。
考察点:
二叉搜索树的建立、树的遍历
思路:
1. 定义结点结构,建立BST;
2. 采用DFS遍历整棵树,搜索过程中把所在层次level作为参数,注意对于每个结点记录其所在层次。
注意点:
1. Insert()参数root必须是结点指针的引用,否则建立动态建立新结点的时候会发生错误。
2. 注意这种记录每个层次结点树的方法。
相关题目:
1. 1043 https://blog.youkuaiyun.com/coderwait/article/details/100168406
2. 1099 https://blog.youkuaiyun.com/coderwait/article/details/100183241
#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
struct Node{
int data;Node* left;Node* right;
Node(int d):data(d),left(NULL),right(NULL){ }
};
int levelCnt[1007]={0};
void Insert(Node* &root,int data){
if(root==NULL){
root = new Node(data);
return;
}
if(data<=root->data) Insert(root->left,data);
else Insert(root->right,data);
}
int maxLevel=0;
void dfs(Node* &root,int level){
if(root!=NULL){
levelCnt[level]++;
maxLevel = max(maxLevel,level);
}
if(root->left!=NULL){
dfs(root->left,level+1);
}
if(root->right!=NULL){
dfs(root->right,level+1);
}
}
int main(void){
int N,a;cin>>N;
Node* root = NULL;
for(int i=0;i<N;i++){
cin>>a;
Insert(root,a);
}
dfs(root,0);
cout<<levelCnt[maxLevel]<<" + "<<levelCnt[maxLevel-1]<<" = "<<levelCnt[maxLevel]+levelCnt[maxLevel-1]<<endl;
return 0;
}