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
总的来说就是下图的意思,请叫我灵魂画手
然后考虑到1000个结点,为了防止测试点构造出来的数比较偏,我们还是乖乖使用二叉链接树吧,新建一个结点结构体,然后慢慢构造成一个BST树。
然后关于如何计算最后两个层次的结点个数,我用的层序遍历,把每层的元素存到vector< int > vec,然后所有的vec存储到vector< vector< int>> out里面
代码:
#include <iostream>
#include <algorithm>
using namespace std;
#include <vector>
#include <queue>
vector<int> vec;
//1000个节点,虽然感觉测试数据不会是太偏的树,但还是别偷懒了,直接结构体走起吧
struct node
{
int data;
node* lchild,*rchild;
node():lchild(NULL),rchild(NULL) {}//所有new的node结点的左右孩子都是NULL
};
void df(node *p,int num)
{
if(num>p->data)
{
if(p->rchild!=NULL)//如果右孩子不为空,就再次深搜
{
df(p->rchild,num);
}
else//不为空就新建一个结点,然后链接到二叉链接树上
{
node *a=new node();
a->data=num;
p->rchild=a;
return ;
}
}
else
{
if(p->lchild!=NULL)
{
df(p->lchild,num);
}
else
{
node *a=new node();
a->data=num;
p->lchild=a;
return ;
}
}
}
int main()
{
int N;
cin>>N;
node *root;
for(int i=0; i<N; i++)
{
if(i==0)//第一次需要构造一下根节点
{
node *a=new node();
cin>>a->data;
root=a;
}
else
{
int num;
cin>>num;
df(root,num);
}
}
queue<node*> que;
que.push(root);//构造队列用于层序遍历
vector<vector<int>> out;//out用来记录每个层次的结点
//下面三行只是确保所给出的二叉树只有2层,我们需要把根节点也存入到out里面
vector<int> vec;
vec.push_back(root->data);
out.push_back(vec);
while(!que.empty())
{
queue<node*> get;
vector<int> vec;
while(!que.empty())
{
node *p=que.front();
int data=p->data;
if(p->lchild!=NULL)
{
get.push(p->lchild);
vec.push_back(p->lchild->data);
}
if(p->rchild!=NULL)
{
get.push(p->rchild);
vec.push_back(p->rchild->data);
}
que.pop();
}
if(vec.size()!=0)
out.push_back(vec);
que=get;
}
cout<<out[out.size()-1].size()<<" + "<<out[out.size()-2].size()<<" = "<<out[out.size()-1].size()+out[out.size()-2].size();
return 0;
}