程序设计基础15 完全二叉排序树

xiaoxiao2021-03-01  37

1064 Complete Binary Search Tree (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 the node's key.The right subtree of a node contains only nodes with keys greater than or equal to the node's key.Both the left and right subtrees must also be binary search trees.

A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.

Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input:

10 1 2 3 4 5 6 7 8 9 0

Sample Output:

6 3 8 1 5 7 9 0 2 4

一,基本思想:

    与普通的二叉排序树不同,完全二叉排序树必须保证是完全二叉树,不过完全二叉排序树表达起来也更简单,可以用数组来表示,即root表示根节点,2*root是左孩子,2*root+1是右孩子,把给出数据从小到大排序,按照中序遍历的顺序依次赋值即可,数组的键表示这是第几号结点,数组的值表示这个结点的值,把数组按顺序输出即为层序遍历的结果。

二,正确代码:

#include<cstdio> #include<algorithm> using namespace std; //到7:50 到8:25 const int max_n = 1100; int n = 0; int index = 0; int arr[max_n] = { 0 }; int CBT[max_n] = { 0 }; void inOrder(int root) { if (root > n)return; inOrder(2 * root); CBT[root] = arr[index++]; inOrder(2 * root + 1); } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } sort(arr, arr + n); inOrder(1); for (int i = 1; i <= n; i++) { printf("%d", CBT[i]); if (i != n) { printf(" "); } } return 0; }

 

转载请注明原文地址: https://www.6miu.com/read-3164287.html

最新回复(0)