A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:node
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.c++
譯:二叉搜索樹 (BST) 遞歸地定義爲具備如下屬性的二叉樹:less
節點的左子樹僅包含鍵小於或等於節點鍵的節點。ide
節點的右子樹僅包含鍵大於節點鍵的節點。測試
左右子樹也必須是二叉搜索樹。idea
將一系列數字插入到最初爲空的二叉搜索樹中。 而後你應該計算結果樹的最低 2 個級別中的節點總數。spa
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.code
譯:每一個輸入文件包含一個測試用例。 對於每種狀況,第一行給出一個正整數 N (≤1000),它是輸入序列的大小。 而後在下一行給出 [−1000,1000] 中的 N 個整數,它們應該被插入到最初爲空的二叉搜索樹中。orm
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 ; }