您的位置:首页 > 其它

PAT甲级.1064. Complete Binary Search Tree (30)

2016-10-23 11:34 495 查看
题目

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.

输入格式

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.

输出格式

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.

输入样例

10

1 2 3 4 5 6 7 8 9 0

输出样例

6 3 8 1 5 7 9 0 2 4

PAT链接

思路

使用二叉树的静态实现方法

1.开一个数组CBT[maxn],其中CBT[1]~CBT
按层序存放完全二叉树的n个结点

2.因为中序遍历序列是递增的,将输入数字从小到大排序,然后对CBT数组表示的二叉树进行中序遍历,并在遍历过程中将数字从小到大填入数组,最后就能得到一课完全二叉排序树。

3.由于CBT数组就是按照二叉树的层序存放结点,因此只需要将数组元素按顺序输出即为层序遍历序列。

代码

/**
* @tag     PAT_A_1064
* @authors R11happy (xushuai100@126.com)
* @date    2016-10-22 14:28-15:18
* @version 1.0
* @Language C++
* @Ranking  700/1626
* @function null
*/

#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int maxn = 1010;
//n为结点数,number用来存放结点权值,CBT用来存放完全二叉树
//index从小到大枚举number数组
int n, number[maxn], CBT[maxn];
int num, index;
/*中序遍历*/
void inOrder(int root)
{
if (root > n)    return; //空结点,直接返回
inOrder(root * 2);    //左子树递归
CBT[root] = number[index++];    //根结点处赋值number[index]
inOrder(root * 2 + 1);  //右子树递归
}

int main(int argc, char const *argv[])
{
scanf("%d", &n);
for (int i = 0; i<n; i++)
{
scanf("%d", &number[i]);
}
sort(number, number + n);
inOrder(1); //根结点的下标必须为1
// 注意i要从1开始
for (int i = 1; i <= n; i++)
{
printf("%d", CBT[i]);
num++;
if (num < n) printf(" ");
}
return 0;
}


收获

1.左子树2x,右子树2x+1

2.根结点下标为1

3.数组元素存放的顺序恰好为完全二叉树的层序遍历序列

4.判断某个结点是否为空结点的标志为:该结点下标root大于结点总个数n

5.判断某个结点是否为叶结点的标志为该结点(记下标root)的左子结点的编号root*2大于结点总个数n
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: