PAT甲1115 Counting Nodes in a BST【dfs】
1115 Counting Nodes in a BST (30 分)
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 [−10001000] 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
題意:
給定n個數,建一棵二叉搜尋樹。問倒數第一層和倒數第二層分別有多少個節點。
思路:
先建樹,然後dfs看每個節點的深度。
1 #include <iostream> 2 #include <set> 3 #include <cmath> 4 #include <stdio.h> 5 #include <cstring> 6 #include <algorithm> 7 #include <vector> 8 #include <queue> 9 #include <map> 10 #include <bits/stdc++.h> 11 using namespace std; 12 typedef long long LL; 13 #define inf 0x7f7f7f7f 14 15 const int maxn = 1005; 16 int n, num[maxn], cnt[maxn], dep = -1; 17 struct node{ 18 int val; 19 int left = -1, right = -1; 20 int height; 21 }tree[maxn]; 22 int tot; 23 24 void add(node t, int rt) 25 { 26 if(t.val > tree[rt].val && tree[rt].right != -1){ 27 add(t, tree[rt].right); 28 } 29 else if(t.val > tree[rt].val){ 30 tree[tot] = t; 31 tree[rt].right = tot++; 32 } 33 else if(tree[rt].left != -1){ 34 add(t, tree[rt].left); 35 } 36 else{ 37 tree[tot] = t; 38 tree[rt].left = tot++; 39 } 40 } 41 42 void dfs(int rt, int h) 43 { 44 tree[rt].height = h; 45 cnt[h]++; 46 dep = max(dep, h); 47 if(tree[rt].left != -1){ 48 dfs(tree[rt].left, h + 1); 49 } 50 if(tree[rt].right != -1){ 51 dfs(tree[rt].right, h + 1); 52 } 53 } 54 55 int main() 56 { 57 scanf("%d", &n); 58 scanf("%d", &tree[tot++].val); 59 for(int i = 1; i < n; i++){ 60 node t; 61 scanf("%d", &t.val); 62 add(t, 0); 63 } 64 65 //printf("!\n"); 66 dfs(0, 1); 67 int n1 = cnt[dep], n2 = cnt[dep - 1]; 68 printf("%d + %d = %d\n", n1, n2, n1 + n2); 69 return 0; 70 }