题目描述
1115 Counting Nodes in a BST (30分)
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 [?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
求解思路
- 题意:给定结点数目n,以及序列。要求我们建立一棵搜索二叉树,并且输出最底端的两层结点数目。
- 按照要求建树即可。
- 层次遍历的时候给结点赋予层号,统计每层的结点数以及最大的层数。
代码实现(AC)
#include<cstdio>
#include<queue>
using namespace std;
struct Node{
int data;
Node *lchild;
Node *rchild;
int level;
};
int n;
int levell[1010]={0},maxlevel=0;
Node* newNode(int value)
{
Node* root=new Node;
root->data=value;
root->lchild=NULL;
root->rchild=NULL;
return root;
}
void insert(Node* &root,int value)
{
if(root==NULL)
{
root=newNode(value);
return;
}
else if(root->data>=value)
insert(root->lchild,value);
else if(root->data<value)
insert(root->rchild,value);
return;
}
void levelTraversal(Node *root)
{
queue<Node*>q;
root->level=1;
q.push(root);
while(!q.empty())
{
Node* t=q.front();
q.pop();
levell[t->level]++;
if(t->level>maxlevel) maxlevel=t->level;
if(t->lchild!=NULL)
{
t->lchild->level=t->level+1;
q.push(t->lchild);
}
if(t->rchild!=NULL)
{
t->rchild->level=t->level+1;
q.push(t->rchild);
}
}
}
void solve()
{
scanf("%d",&n);
Node *root=NULL;
for(int i=0;i<n;i++)
{
int tmp;
scanf("%d",&tmp);
insert(root,tmp);
}
levelTraversal(root);
printf("%d + %d = %d",levell[maxlevel],levell[maxlevel-1],levell[maxlevel]+levell[maxlevel-1]);
}
int main()
{
solve();
return 0;
}