PAT(树)——1115 Counting Nodes in a BST (30 分)

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

题目大意:

求给出一串数字建立二叉搜索树,然后求最底下两级的元素个数。

题目解析:

可以用指针的方法,也可以用数组(如下),在建立搜索树的时候存储级别,最后遍历数组。

具体代码:

#include<iostream>
#include<algorithm>
using namespace std;
struct node{
	int level;
	int key;
	int left=-1,right=-1;
}A[1100];
int maxlevel=0;
void addnode(int root,int child,int level){
	if(level>maxlevel)
		maxlevel=level;
	if(A[child].key<=A[root].key){
		if(A[root].left==-1){
			A[root].left=child;
			A[child].level=level;
		}
		else
			addnode(A[root].left,child,level+1);
	}else{
		if(A[root].right==-1){
			A[root].right=child;
			A[child].level=level;
		}
		else
			addnode(A[root].right,child,level+1);
	}
}
int main()
{
    int n;
    cin>>n;
    cin>>A[0].key;
    A[0].level=0;
    for(int i=1;i<n;i++){
    	cin>>A[i].key;
    	addnode(0,i,1);
	}
	int n1=maxlevel,n2=maxlevel-1;
	int count1=0,count2=0;
	for(int i=0;i<n;i++){
		if(A[i].level==n1)
			count1++;
	}
	for(int i=0;i<n;i++){
		if(A[i].level==n2)
			count2++;
	}
	printf("%d + %d = %d",count1,count2,count1+count2);
    return 0;
}
全部评论
感谢,我也是想当然了,大于等于放右边了。
点赞 回复 分享
发布于 2021-02-05 22:16

相关推荐

03-05 12:52
吉林大学 Java
挣K存W养DOG:他的价值在于把他家里积攒的财富回馈给社会
点赞 评论 收藏
分享
序&nbsp;朋友们,好久不见。&nbsp;笔者在过去消失的五个月里被困在情绪牢笼中过的相当煎熬,一度丢失自己,觉得整个世界都是昏暗的。&nbsp;庆幸的是靠着自己纯硬扛也是走出来了。表达欲再度回归,所以真的很开心还有机会能在再和大家见面。&nbsp;破碎秋招&nbsp;抑郁情绪的引爆点必然是秋招期间遭受的打击了,从去年九月份腾讯转正被告知失败之后就开始疯狂投递简历,每天都在经历:简历挂、一面挂、二面挂、三面挂、HR面挂,每天睁开眼就被无所适从的挫败感包围。&nbsp;秋招的特点是即便流程走到最后一步也不一定会&nbsp;offer,因为还需要进入大池子进行横向对比,俗称泡池子,而这一泡我的大多数面试流程到后面就没了后文,这一度让我感觉非常绝望。我深知自己学历并...
SoNiC_X:我已经工作快2年了,当时高考没考好没去到想去的学校,觉得天要塌了;校招找不到工作,觉得天要塌了;现在工作觉得看不到未来,觉得天要塌了;最近最大的感悟就是:天会一直塌,但是生活也会一直继续下去,还是要调整好自己的心态,不要因为一时的困难把自己困住,要记住完蛋的日子永远在后头
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务