这道题大意是这样,输入N个不同的非负整数,需要将其按照二叉搜索树的规则,排成一个完全二叉树。二叉搜索树是指每个每个节点的所有左元素都比它小,右边都比它大;完全二叉树指的是,除了最后一层,其余每一层都满,最后一层从左往右排。 之后层序遍历,输出。
一开始想法是,构造,然后输出。并不能码出来(水平不够)
之后去查了别人的算法,又被别人的机智惊艳到了!
基本想法是这样,完全二叉树有这么一个性质,若a节点的下标为i,那么它左儿子的下标为2i,右儿子为2i+1. 而这个下标则为完全二叉树在层序遍历时的输出顺序。而对于任意一棵搜索树,其中序遍历的输出,是一个递增的数列。根据这两个性质,可以有如下算法。
首先,将输入的数列递增排序,会用到qsort函数。这样,得到了所求的完全二叉搜索树的中序遍历输出,得到数组a[i]。接着,根据总的节点个数,将这个完全二叉搜索树的层序遍历的顺序(或者下标),中序遍历输出,得到数组b[i]。则对该完全二叉搜索书的层序遍历的解 c[ b[i] ]=a[i].
如果太抽象,可以这么理解。我现在有一棵完全的二叉搜索树,每个节点上除了 data,left以及right以外,还有一个flag,用来记录他是第几个元素(按照层序遍历的顺序)。现在我有它的中序遍历的输出,那么,只要在这个中序遍历的输出里面,按照每个节点对应的层序遍历的flag,输出,就是层序遍历的输出值了。
对于如何中序的输出层序遍历的顺序,可以参考如何中序的输出节点。类比得:终止条件,输入的 i 大于总的元素数N。递归的顺序,root的顺序是i,则先让2i入递归,然后输出i,接着让2i+1入递归。
#include <stdio.h>
#include <stdlib.h>
int b[1005];
int j=0;
int compare(const void * a, const void * b);
void mid_tre(int root,int N,int a[]);
int main(){
int N;
int i=0;
scanf("%d",&N);
int a[N];
for(i=0;i<N;i++){
scanf("%d",&a[i]);
}
qsort(a,N,sizeof(int),compare);
mid_tre(1,N,a);
printf("%d",b[1]);
for(i=2;i<=N;i++){
printf(" %d",b[i]);
}
}
int compare(const void * a, const void * b)
{
return *(int *)a - *(int *)b;
}
void mid_tre(int root,int N,int a[]){
if(root<=N){
mid_tre(2*root,N,a);
b[root]=a[j++];
mid_tre(2*root+1,N,a);
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
04-树6 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