PAT_A1115#Counting Nodes in a BST
Source:
Description:
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 (≤) which is the size of the input sequence. Then given in the next line are the N integers in [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, andn
is the sum.
Sample Input:
9 25 30 42 16 20 20 35 -5 28
Sample Output:
2 + 4 = 6
Keys:
Attention:
- BST定义有时候会不一样,等号跟左子树还是右子树要看清楚,注意审题
Code:
1 /* 2 Data: 2019-06-26 15:55:13 3 Problem: PAT_A1115#Counting Nodes in a BST 4 AC: 17:15 5 6 题目大意: 7 BST定义:lchild <= root < rchild 8 根据插入序列建立BST树,统计最底层和次底层的结点数量 9 10 基本思路: 11 建树,记录结点层次,全局变量记录树的最大深度 12 更新最大深度的同时,统计底层和次底层的结点个数 13 */ 14 #include<cstdio> 15 int deep=0,n1=0,n2=0; 16 struct node 17 { 18 int data; 19 node *lchild,*rchild; 20 }; 21 22 void Insert(node *&root, int x, int height) 23 { 24 if(root == NULL) 25 { 26 if(deep == height) 27 n1++; 28 else if(deep == height+1) 29 n2++; 30 else if(deep == height-1) 31 { 32 deep++; 33 n2 = n1; 34 n1 = 1; 35 } 36 root = new node; 37 root->data = x; 38 root->lchild = root->rchild = NULL; 39 } 40 else if(x <= root->data) 41 Insert(root->lchild, x, height+1); 42 else 43 Insert(root->rchild, x, height+1); 44 } 45 46 int main() 47 { 48 #ifdef ONLINE_JUDGE 49 #else 50 freopen("Test.txt", "r", stdin); 51 #endif // ONLINE_JUDGE 52 53 int n,x; 54 scanf("%d", &n); 55 node *root = NULL; 56 for(int i=0; i<n; i++) 57 { 58 scanf("%d", &x); 59 Insert(root,x,1); 60 } 61 printf("%d + %d = %d", n1,n2,n1+n2); 62 63 return 0; 64 }