1115 Counting Nodes in a BST(构建搜索二叉树)

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

本题题意就是:

  根据题意给出的结点构建一颗搜索二叉树 并计算出倒数第一层 与 倒数第二层的结点和

 本题的思路就是:

 1.本题没有告诉具体的 结点的id 只是告诉结点的值, 用链表构建二叉搜索树

 2. 递归建树 时 用一个数组num[i] 存储高度(这里高度为深度)为i的结点个数 (递归时记录高度)

具体代码:

/**
题意:
		找到搜索二叉树倒数第一层的结点,与倒数第二层的结点数,并相加 
本题思路 1.构建搜索二叉树
		 2. 再次递归遍历搜索二叉树将每层高度的结点计算并放入hnum[i]
		 数组中(高度为i的树中节点的个数) 
**/
#include<iostream>
using namespace std;
struct Node{
	int data;
	Node *l, *r;
};
int n, hmax = -1, hnum[1000];
void createBST(Node *&root, int data){
	if(root == nullptr){
		root = new Node();
		root->data = data;
		return; 
	}else if(data <= root->data){
		createBST(root->l, data);
	}else if(data > root->data){
     	createBST(root->r, data);
	}  
} 
void dfs(Node *&root, int h){
	if(root == nullptr) return;
	hmax = max(h, hmax);
	hnum[h]++;
	dfs(root->l, h+1);
	dfs(root->r, h+1);
}ss 
int main(){
	Node *root = nullptr;
	int data;
	scanf("%d", &n);
	while(n--){
		scanf("%d", &data);
		createBST(root,data);
	}
	dfs(root, 0);
	printf("%d + %d = %d",hnum[hmax], hnum[hmax-1], hnum[hmax] + hnum[hmax - 1]);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_41698081/article/details/91404422
今日推荐