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
结题思路:
题意要求我们对构建的树,分别计算最后两层的节点个数。
要求1:考察二叉搜索树的建立过程;
要求2:比跟节点大的插入到右子树,小于等于根节点的插入到左子树。
程序步骤:
第一步:建立二叉搜索树;
第二步:由于每个插入的新节点都位于叶子节点,故我们可以利用空间换取时间的思想,为每个节点增设depth属性,当前插入节点的depth=cur.parent.depth+1,由于当前插入为叶子,故其父亲节点depth必不为空;
第三步:遍历二叉搜索树所存储的数组,分别统计最后两层的节点个数。
具体程序(AC)如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct node{
int depth;
int value;
int left;
int right;
node():depth(0),value(-2000),left(-1),right(-1){}
};
vector<node> tree;
int no=1;
int deepest=0;
void pushIn2BTree(int root,int value)
{
if(value>tree[root].value)
{
if(tree[root].right==-1)
{
tree[no].value=value;
tree[no].depth=tree[root].depth+1;
if(tree[no].depth>deepest)
deepest=tree[no].depth;
tree[root].right=no;
no++;
}
else
pushInBTree(tree[root].right,value);
}
else
{
if(tree[root].left==-1)
{
tree[no].value=value;
tree[no].depth=tree[root].depth+1;
if(tree[no].depth>deepest)
deepest=tree[no].depth;
tree[root].left=no;
no++;
}
else
pushInBTree(tree[root].left,value);
}
}
int main()
{
int n,value;
cin>>n;
tree.resize(n);
if(n==0)
{
cout<<"0 + 0 = 0"<<endl;
return 0;
}
else
{
cin>>tree[0].value;
for(int i=1;i<n;++i)
{
cin>>value;
pushIn2BTree(0,value);
}//建树完成
if(deepest==0)
cout<<"1 + 0 = 1"<<endl;
else
{
int last=0,beforeLast=0;
for(int i=0;i<n;++i)
{
if(tree[i].depth==deepest)
++last;
else if(tree[i].depth==deepest-1)
++beforeLast;
}
cout<<last<<" + "<<beforeLast<<" = "<<last+beforeLast<<endl;
}
}
return 0;
}