关闭

1064. Complete Binary Search Tree (30)

标签: PAT完全二叉树二叉排序树层序遍历BFS中序遍历PreOrder
85人阅读 评论(0) 收藏 举报
分类:
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


IDEA

1.完全二叉排序树,设每个节点序号为 i属于[0~n-1],则其左孩子序号为2*i+1,右孩子为2*i+2

2.二次排序树进行中序遍历后,得到节点值排序是从小到大的序列


CODE

#include<iostream>
#include<vector> 
#include<queue>
#include<algorithm>
#include<fstream>
using namespace std;
#define MAX 1001
struct Node{
	int data;
	int left,right;
};
Node tree[MAX];
int data[MAX];
int n;
void InOrder(int root){
	static int index=0;
	if(root>=n){
		return;
	}
	InOrder(tree[root].left);
	tree[root].data=data[index++];
	//cout<<root<<" "<<tree[root].data<<endl;
	InOrder(tree[root].right);
}
void LevelOrder(int root,vector<int> &seq){
	queue<int> que;
	que.push(root);
	while(!que.empty()){
		int tmp=que.front();
		que.pop();
		seq.push_back(tree[tmp].data);
		if(tree[tmp].left<n){
			que.push(tree[tmp].left);
		}
		if(tree[tmp].right<n){
			que.push(tree[tmp].right);
		}
	}
}
int main(){
	#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	#endif
	
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>data[i];
	}
	sort(data,data+n);
	
	for(int i=0;i<n;i++){
		tree[i].left=2*i+1;
		tree[i].right=2*i+2;		
	}
	
	int root=0;
	InOrder(root);
	
	vector<int> seq;
	LevelOrder(root,seq);
	
	vector<int>::iterator it;
	for(it=seq.begin();it!=seq.end();it++){
		if(it==seq.begin()){
			cout<<*it;
		}else{
			cout<<" "<<*it;
		}
	}	
	#ifndef ONLINE_JUDGE
	fclose(stdin);
	#endif
	
	return 0;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:22279次
    • 积分:2402
    • 等级:
    • 排名:第15506名
    • 原创:230篇
    • 转载:2篇
    • 译文:0篇
    • 评论:5条
    最新评论