您的位置:首页 > Web前端 > Node.js

1115. Counting Nodes in a BST (30)

2016-12-21 11:33 323 查看
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

题目大意:就是给出数组,生成二叉搜索树,输出最下面两层的节点树。思路:就是生成二叉搜索树,在生成的过程中,用level数组记录每层的个数以及记录最大的层数。注意:n=1时候,输出1+0=1

#include <iostream>
using namespace std;
const int maxn = 1005;
int level[maxn];
int n, maxdepth = -1;
typedef struct Node{
int x;
struct Node* left;
struct Node* right;
} Node;
Node* insert(int x, Node* tree, int l)
{
if(tree == NULL){
tree = new Node();
if(tree == NULL)
printf("create failed!");
else{
tree->x = x;
tree->left = NULL;
tree->right = NULL;
level[l]++;
maxdepth = max(l, maxdepth);
}
} else if(x <= tree->x)
tree->left = insert(x, tree->left, l + 1);
else if(x > tree->x)
tree->right = insert(x, tree->right, l + 1);
return tree;
}
int main()
{
Node *tree = NULL;
scanf("%d", &n);
int x;
for(int i = 0; i < n; ++i){
scanf("%d", &x);
tree = insert(x, tree, 0);
}
printf("%d + %d = %d\n", level[maxdepth], level[maxdepth - 1], level[maxdepth] + level[maxdepth - 1]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pat