A1115. Counting Nodes in a BST (30)

来源:互联网 发布:上位机用什么编程 编辑:程序博客网 时间:2024/05/20 07:34

题目描述

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:
925 30 42 16 20 20 35 -5 28
Sample Output:
2 + 4 = 6

参考代码

#include <cstdio>#include <malloc.h>#include <queue>using namespace std;const int maxn = 1100;struct Node{int data;int step;struct Node * lchild;struct Node * rchild;};int N,a[maxn],maxLevel = -1,num[maxn]={0};void createBST(int data,Node * node,Node * child,int flag){if(child == NULL){Node * newNode = (Node *)malloc(sizeof(Node));newNode->data = data;newNode->step = node->step + 1;if(newNode->step > maxLevel){maxLevel = newNode->step;}newNode->lchild = NULL;newNode->rchild = NULL;if(flag == 1)node->lchild = newNode;else if(flag == 2)node->rchild = newNode;return;}if(data <= child->data){Node * next = child->lchild;createBST(data,child,next,1);}else{Node * next = child->rchild;createBST(data,child,next,2);}}void levelOrder(Node * root){queue<Node *> q;q.push(root);while(!q.empty()){Node * node = q.front();q.pop();num[node->step]++;if(node->lchild != NULL){q.push(node->lchild);}if(node->rchild != NULL){q.push(node->rchild);}}}int main(){Node * root;scanf("%d",&N);for(int i=0;i<N;i++){scanf("%d",&a[i]);}for(int i=0;i<N;i++){if(i == 0){root = (Node *)malloc(sizeof(Node));root->data = a[i];root->step = 1;root->lchild = NULL;root->rchild = NULL;}else{if(a[i] <= root->data){createBST(a[i],root,root->lchild,1);}else{createBST(a[i],root,root->rchild,2);}}}levelOrder(root);if(N != 1){printf("%d + %d = %d",num[maxLevel],num[maxLevel - 1],num[maxLevel] + num[maxLevel - 1]);}else{printf("1 + 0 = 1");}return 0;}


0 0
原创粉丝点击