1. 程式人生 > >《資料結構》04-樹6 Complete Binary Search Tree

《資料結構》04-樹6 Complete Binary Search Tree

題目

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

分析

大概題意是:給定一組二叉搜尋樹插入值,使得剛好該二叉搜尋樹是棵完全二叉樹,輸出組成該樹的值的層序遍歷

考慮到連結串列的層序遍歷還得單獨實現,採用陣列實現二叉搜尋樹 整體框架是一個先序遍歷,由於給了一組輸入,排好序就成了該二叉搜尋樹的中序序列,利用完全二叉樹的性質可以求出左子樹結點個數,從而遞迴填充根結點

#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#define MaxSize 2005
using namespace std;
int value[MaxSize];
int BST[MaxSize];

// 計算 n 個結點的樹其左樹結點個數 
int getLeftTreeSize(int n){
	int h =0;   // 儲存該結點下滿二叉樹的層數 
	int tmp = n+1;
	while(tmp!=1){
		tmp /=2;
		h++;
	}
	int x = n-pow(2,h)+1;   // 最下面一排子葉結點個數 
	x = x<pow(2,h-1)?x:pow(2,h-1);   // 子葉結點個數最多是 2^(h-1) 
	int L = pow(2,h-1)-1+x;   // 該結點個數情況下左子樹的個數 
	return L;
}

// 填充函式
void fill(int left,int right,int root){
	int n = right - left + 1;  // 確定範圍內數值個數 
 	if(!n)
 		return;
 	int L = getLeftTreeSize(n);   // 找到"偏移量" 
 	BST[root] = value[left + L];    // 根結點的值應該是 左邊界值 + 偏移量 
 	int leftRoot = 2 * root + 1;   // 左兒子結點位置,由於從 0 開始 
 	int rightRoot = leftRoot + 1;  // 右兒子結點位置 
 	fill(left,left+L-1,leftRoot);  // 左子樹遞迴 
 	fill(left+L+1,right,rightRoot);   // 右子樹遞迴 
}

int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>value[i];
	}
	// 從小到大排序 
	sort(value,value+n);
	fill(0,n-1,0);
	for(int i=0;i<n;i++){
		if(i)
			cout<<" ";
		cout<<BST[i];
	}
	return 0;
}