A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
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.
译:二叉搜索树 (BST) 递归地定义为具有以下属性的二叉树:
节点的左子树仅包含键小于或等于节点键的节点。
节点的右子树仅包含键大于节点键的节点。
左右子树也必须是二叉搜索树。
将一系列数字插入到最初为空的二叉搜索树中。 然后你应该计算结果树的最低 2 个级别中的节点总数。
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.
译:每个输入文件包含一个测试用例。 对于每种情况,第一行给出一个正整数 N (≤1000),它是输入序列的大小。 然后在下一行给出 [−1000,1000] 中的 N 个整数,它们应该被插入到最初为空的二叉搜索树中。
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.
译:对于每种情况,在一行中打印结果树的最低 2 级中的节点数,格式如下:
n1 + n2 = n
其中 n1 是最低层的节点数,n2 是上层的节点数,n 是总和。
9 25 30 42 16 20 20 35 -5 28
2 + 4 = 6
#include<bits/stdc++.h> using namespace std ; const int maxn = 1010 ; int n , t , cnt = 0 ; vector<int> ans ; struct node{ int val ; node* l ; node* r ; }; void insert(node* &root , int data){ if(!root){ root = new node() ; root->val = data ; root->l = root->r = NULL ; return ; // 一定要记得返回,不然会爆栈 } if(data <= root->val) insert(root->l , data) ; else insert(root->r , data) ; } void bfs(node* root){ queue<node*> q ; q.push(root) ; while(!q.empty()){ cnt ++ ; // 记录总共有几层 int size = q.size() ; ans.push_back(size ); for(int i = 0 ; i < size ; i ++){ node* top = q.front() ; q.pop() ; if(top->l != NULL) q.push(top->l) ; // 左孩子不空,则入队 if(top->r != NULL) q.push(top->r) ; // 右孩子不空,则入队 } } } int main(){ cin >> n ; node* root = NULL ; for(int i = 0 ; i < n ; i ++){ cin >> t ; insert(root , t) ; } bfs(root) ; printf("%d + %d = %d\n" , ans[cnt - 1] , ans[cnt - 2] , ans[cnt - 1] + ans[cnt - 2]) ; return 0 ; }