1. 程式人生 > 其它 >PAT (Advanced Level) Practice 1115 Counting Nodes in a BST (30 分) 凌宸1642

PAT (Advanced Level) Practice 1115 Counting Nodes in a BST (30 分) 凌宸1642

PAT (Advanced Level) Practice 1115 Counting Nodes in a BST (30 分) 凌宸1642

題目描述:

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.

譯:二叉搜尋樹 (BST) 遞迴地定義為具有以下屬性的二叉樹:

  • 節點的左子樹僅包含鍵小於或等於節點鍵的節點。

  • 節點的右子樹僅包含鍵大於節點鍵的節點。

  • 左右子樹也必須是二叉搜尋樹。

將一系列數字插入到最初為空的二叉搜尋樹中。 然後你應該計算結果樹的最低 2 個級別中的節點總數。


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.

譯:每個輸入檔案包含一個測試用例。 對於每種情況,第一行給出一個正整數 N (≤1000),它是輸入序列的大小。 然後在下一行給出 [−1000,1000] 中的 N 個整數,它們應該被插入到最初為空的二叉搜尋樹中。


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.

譯:對於每種情況,在一行中列印結果樹的最低 2 級中的節點數,格式如下:

n1 + n2 = n

其中 n1 是最低層的節點數,n2 是上層的節點數,n 是總和。


Sample Input (樣例輸入):

9
25 30 42 16 20 20 35 -5 28

Sample Output (樣例輸出):

2 + 4 = 6

The Idea:

  • 節點數不多,利用鏈式二叉樹結構,根據輸入的資料,簡歷二叉搜尋樹 BST。
  • 對二叉搜尋樹進行層序遍歷,並且記錄層數以及每層節點的個數。
  • 輸出最後兩層的算術和的算式。

The Codes:

#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 ;
}