题目
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 ) N(\le1000) N(≤1000) which is the size of the input sequence. Then given in the next line are the N N N integers in [ − 1000 , 1000 ] [−1000,1000] [−1000,1000] 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
题目大意
给出一个序列,建立二叉搜索树BST,要求计算出这个二叉搜索树最低两层节点数量。
思路
按照所给序列建树,然后层次遍历,用vector记录每层结点数,最后输出vector后两位即可。
代码
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
struct node{
int data;
node *left, *right;
};
node *root = NULL;
void insertBST(node *r, int t){
if(t <= r->data){
if(r->left == NULL){
node *p = new node;
p->data = t;
p->left = p->right = NULL;
r->left = p;
}
else
insertBST(r->left, t);
}
else{
if(r->right == NULL){
node *p = new node;
p->data = t;
p->left = p->right = NULL;
r->right = p;
}
else
insertBST(r->right, t);
}
}
int main(){
int n;
scanf("%d", &n);
for(int i=0, t; i<n; i++){
scanf("%d", &t);
if(root == NULL){
root = new node;
root->data = t;
root->left = root->right = NULL;
}
else
insertBST(root, t);
}
vector<int> ans;
queue<node*> que;
que.push(root);
while(!que.empty()){
int t = que.size();
ans.push_back(t);
for(int i=0; i<t; i++){
node *temp = que.front();
que.pop();
if(temp->left != NULL)
que.push(temp->left);
if(temp->right != NULL)
que.push(temp->right);
}
}
int t = ans.size();
printf("%d + %d = %d\n", ans[t-1], ans[t-2], ans[t-1]+ans[t-2]);
return 0;
}