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
题目大意
构造一棵二叉排序树,然后统计树的最后两行的结点数
思路
正常构建排序树,然后通过DFS得到行数,再通过BFS得到最后两行的结点数
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct node
{
int val;
node* left;
node* right;
node(int v) : val(v), left(NULL), right(NULL) {}
};
int level;
vector<int> vec;
node* creat();
void insert(node* &, int);
void getLevel(node*, int);
void getAns(node*, int&, int&);
int main()
{
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
int val;
cin >> val;
vec.push_back(val);
}
node* root = creat();
getLevel(root, 1);
if (level == 1)
cout << 1 << " + 0" << " = " << 1 << endl;
else if (level == 2)
{
int n2 = 1, n1 = 0;
if (root->left != NULL)
n1++;
if (root->right != NULL)
n1++;
cout << n1 << " + " << n2 << " = " << n1 + n2 << endl;
}
else
{
int n1, n2;
getAns(root, n2, n1);
cout << n1 << " + " << n2 << " = " << n1 + n2 << endl;
}
return 0;
}
node* creat()
{
node* root = NULL;
for (int i = 0; i < vec.size(); i++)
insert(root, vec[i]);
return root;
}
void insert(node* &root, int v)
{
if (root == NULL)
{
root = new node(v);
return;
}
if (v <= root->val)
insert(root->left, v);
else
insert(root->right, v);
}
void getLevel(node* root, int step)
{
if (step > level)
level = step;
if (root->left != NULL)
getLevel(root->left, step + 1);
if (root->right != NULL)
getLevel(root->right, step + 1);
}
void getAns(node* root, int &a, int &b)
{
int curLevel = 1, ans = 0;
queue<node*> Q;
Q.push(root);
while (!Q.empty())
{
int size = Q.size();
for (int i = 0; i < size; i++)
{
node* front = Q.front();
if (front->left != NULL)
Q.push(front->left);
if (front->right != NULL)
Q.push(front->right);
Q.pop();
}
curLevel++;
if (level - 1 == curLevel) //如果是倒数第二行
a = Q.size();
if (level == curLevel) //如果是最后一行
b = Q.size();
}
}