A1115. Counting Nodes in a BST

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 [-1000 1000] 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 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<string>
 5 #include<queue>
 6 using namespace std;
 7 typedef struct NODE{
 8     struct NODE *lchild, *rchild;
 9     int data;
10     int level;
11 }node;
12 void insert(node* &root, int x){
13     if(root == NULL){
14         node* temp = new node;
15         temp->lchild = NULL;
16         temp->rchild = NULL;
17         temp->data = x;
18         root = temp;
19         return;
20     }
21     if(x <= root->data)
22         insert(root->lchild, x);
23     else insert(root->rchild, x);
24 }
25 int depth = 0, n1, n2;
26 void levelOrder(node* root){
27     queue<node*> Q;
28     root->level = 1;
29     Q.push(root);
30     while(Q.empty() == false){
31         node* temp = Q.front();
32         depth = temp->level;
33         Q.pop();
34         if(temp->lchild != NULL){
35             temp->lchild->level = temp->level + 1;
36             Q.push(temp->lchild);
37         }
38         if(temp->rchild != NULL){
39             temp->rchild->level = temp->level + 1;
40             Q.push(temp->rchild);
41         }
42     }
43 }
44 void DFS(node * root){
45     if(root == NULL)
46         return;
47     if(root->level == depth)
48         n1++;
49     else if(root->level == depth -1)
50         n2++;
51     DFS(root->lchild);
52     DFS(root->rchild);
53 }
54 int main(){
55     int N, temp;
56     node* root = NULL;
57     scanf("%d", &N);
58     for(int i = 0; i < N; i++){
59         scanf("%d", &temp);
60         insert(root, temp);
61     }
62     levelOrder(root);
63     DFS(root);
64     printf("%d + %d = %d", n1, n2, n1 + n2);
65     cin >> N;
66     return 0;
67 }
View Code

 总结:

1、注意最下面两层,和叶节点+叶节点上一层节点个数是不一样的。

原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/8576760.html