学数据结构的时候刷到的一道题,感觉和平时的思路不大一样。并且涉及到完全二叉树上一个重要特性——根据下标访问父节点、子节点。
题目概述:
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.
解题思路为先将输入的数据排序,快排之类的可以调用c语言自带的库函数qsort,也可以自己写。
此外由于二叉树的特性不难发现从小到大排序后的数列为树的中序遍历结果,记为a[]。结合完全二叉树的特性,可以将每一个结点标上下标,中序遍历完全二叉树输出下标的结果存储在b[]。c[b[i]]=a[i]。c[]就是存储该完全二叉树的数组。
要得到中序遍历的树的下标也很简单,从i=1开始,i*2为左儿子的下标,i*2+1为右儿子的下标。
**中序遍历,先递归左儿子,再处理根节点,再递归处理右儿子。
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 1000
int data[MAXSIZE];
int tree[MAXSIZE];
int pos=1;
void build(int data,int size);
int cmp(const void*,const void*);
int main(void)
{
int num;
int temp;
int i=0;
scanf("%d",&num);
temp=num;
while(num--)
{
scanf("%d",&data[++i]);
}
qsort(data+1, i, sizeof(int),cmp);
build(1, i);
for(i=1;i<temp;i++)
{
printf("%d ",tree[i]);
}
printf("%d\n",tree[i]);
}
int cmp(const void*a,const void*b)
{
return *(int*)a-*(int*)b;
}
void build(int root,int size)
{
if(root>size)
return;
build(root*2, size);
tree[root]=data[pos++];
build(root*2+1,size);
}
Sample Input:
10
1 2 3 4 5 6 7 8 9 10
Sample Output:
6 3 8 1 5 7 9 0 2 4