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
【分析】二叉搜索树,计算最高两层的节点数量
总结:
1. BST 的建立
2. bfs dfs 都可以的情况下考虑dfs(代码少还好写)
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
const int maxn = 1e3 + 5;
int n;
int num[maxn];
struct node {
int data;
node* lchild;
node* rchild;
int h;
};
node* newNode(int x) {
node* root = new node;
root->data = x;
root->lchild = NULL;
root->rchild = NULL;
return root;
}
void insertBST(node* &root, int x) {
if (root == NULL) {
root = newNode(x);
return ;
}
if (x <= root->data) insertBST(root->lchild, x);
else {
insertBST(root->rchild, x);
}
}
node* create(int n) {
node* root = NULL;
for (int i = 0; i < n; i++) insertBST(root, num[i]);
return root;
}
int h[maxn];
int ans = 0;
void dfs(node* root, int height) {
if (!root) return ;
ans = max(height, ans);
h[height]++;
if (root->lchild) dfs(root->lchild, height + 1);
if (root->rchild) dfs(root->rchild, height + 1);
}
void bfs(node* root) {
fill(h, h + maxn, 0);
queue<node*> q;
q.push(root);
root->h = 0;
h[ans] = 1;
while (!q.empty()) {
node* p = q.front(); q.pop();
if (p->lchild) {
q.push(p->lchild);
ans = p->h + 1;
p->lchild->h = ans;
h[ans]++;
}
if (p->rchild) {
q.push(p->rchild);
ans = p->h + 1;
p->rchild->h = ans;
h[ans]++;
}
}
}
void solve() {
node* root = create(n);
bfs(root);
// dfs(root, ans);
int num = h[ans] + h[ans - 1];
printf("%d + %d = %d", h[ans], h[ans - 1], num);
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) scanf("%d", &num[i]);
solve();
return 0;
}