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
 #include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<queue>
using namespace std;
typedef struct NODE{
struct NODE *lchild, *rchild;
int data;
int level;
}node;
void insert(node* &root, int x){
if(root == NULL){
node* temp = new node;
temp->lchild = NULL;
temp->rchild = NULL;
temp->data = x;
root = temp;
return;
}
if(x <= root->data)
insert(root->lchild, x);
else insert(root->rchild, x);
}
int depth = , n1, n2;
void levelOrder(node* root){
queue<node*> Q;
root->level = ;
Q.push(root);
while(Q.empty() == false){
node* temp = Q.front();
depth = temp->level;
Q.pop();
if(temp->lchild != NULL){
temp->lchild->level = temp->level + ;
Q.push(temp->lchild);
}
if(temp->rchild != NULL){
temp->rchild->level = temp->level + ;
Q.push(temp->rchild);
}
}
}
void DFS(node * root){
if(root == NULL)
return;
if(root->level == depth)
n1++;
else if(root->level == depth -)
n2++;
DFS(root->lchild);
DFS(root->rchild);
}
int main(){
int N, temp;
node* root = NULL;
scanf("%d", &N);
for(int i = ; i < N; i++){
scanf("%d", &temp);
insert(root, temp);
}
levelOrder(root);
DFS(root);
printf("%d + %d = %d", n1, n2, n1 + n2);
cin >> N;
return ;
}

总结:

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

上一篇:异常-----Can't convert the date to string, because it is not known which parts of the date variable are in use. Use ?date, ?time or ?datetime built-in, or ?string.\u003Cformat> or ?string(format) built-


下一篇:[Oracle]UNIX与Windows 2000上Oracle的差异(I)