PAT甲级——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

题目大意:根据给出的数据建立二叉搜索树,然后将最深和次深的节点数量相加输出。

思路:建立二叉搜索树的时候要记录每个节点的深度,然后一次DFS找出符合条件的节点并记录数量。需要注意的是题目要求左子树是小于等于当前节点的,判断条件里的等于号不能忘记。比较水的题目就会留坑,这里的等于号就是个大坑~

#include <iostream>
using namespace std;
typedef struct node *BST;
struct node {
	int key, level = 0;
	BST left = NULL, right = NULL;
};
int depth = 0, n1 = 0, n2 = 0;
int max(int a, int b);
BST buildTree(BST tree, int &key, int level);
void DFS(BST tree);
int main()
{
	int N, n;
	scanf("%d", &N);
	BST tree = NULL;
	for (int i = 0; i < N; i++) {
		int key;
		scanf("%d", &key);
		tree = buildTree(tree, key, 1);
	}
	DFS(tree);
	n = n1 + n2;
	printf("%d + %d = %d\n", n1, n2, n);
}
void DFS(BST tree) {
	if (tree) {
		if (tree->level == depth - 1) 
			n2++;
		if (tree->level == depth) 
			n1++;
		DFS(tree->left);
		DFS(tree->right);
	}
}
BST buildTree(BST tree, int &key, int level) {
	if (tree == NULL) {
		tree = new node();
		tree->key = key;
		tree->level = level;
	}
	else if (key <= tree->key) {
		tree->left = buildTree(tree->left, key, level + 1);
	}
	else {
		tree->right = buildTree(tree->right, key, level + 1);
	}
	depth = max(depth, level);
	return tree;
}
int max(int a, int b) {
	return a > b ? a : b;
}

猜你喜欢

转载自blog.csdn.net/weixin_44385565/article/details/89879789
今日推荐