1064.Complete Binary Search Tree

【題意】
        給出一個BST的所有元素,要求這個BST同時是完全二叉樹,輸出這個二叉樹的層先遍歷序列

【思路】

        對於一個完全二叉樹,總的節點數給出後左右子樹的節點數就確定了,再結合BST的中序遍歷是遞增數列的特性,就可以遞歸地建樹了。層先遍歷自然是藉助隊列實現


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;

vector<int> numbers;

typedef struct node{
	int value;
	node *left;
	node *right;
}BiNode;

void nodeCnt(int n, int *leftCnt, int *rightCnt){
	int h;

	h = (int)(log(n*1.0)/log(2.0))+1;
	if(h==1){
		*leftCnt = *rightCnt = 0;
	}
	else{
		if(3*pow(2.0,h-2)-1>=n){
			*rightCnt = pow(2.0,h-2)-1;
			*leftCnt = n-1-*rightCnt;
		}
		else{
			*leftCnt = pow(2.0,h-1)-1;
			*rightCnt = n-1-*leftCnt;
		}
	}
}

BiNode *buildTree(int leftIndex, int rightIndex){
	int n,leftCnt,rightCnt;
	BiNode *father;

	n = rightIndex-leftIndex+1;
	father = (BiNode*)malloc(sizeof(BiNode));
	nodeCnt(n,&leftCnt,&rightCnt);
	father->value = numbers[leftIndex+leftCnt];
	if(leftCnt==0){
		father->left = NULL;
	}
	else{
		father->left = buildTree(leftIndex,leftIndex+leftCnt-1);
	}
	if(rightCnt==0){
		father->right = NULL;
	}
	else{
		father->right = buildTree(rightIndex-rightCnt+1,rightIndex);
	}
	return father;
}

int main(int argc, char const *argv[])
{
	int n;

	cin >> n;
	numbers.resize(n);
	for(int i=0; i<n; i++){
		cin >> numbers[i];
	}
	sort(numbers.begin(),numbers.end());

	BiNode *head = buildTree(0,n-1);

	bool first = true;
	queue<BiNode*> qq;
	qq.push(head);
	while(!qq.empty()){
		if(first){
			first = false;
		}
		else{
			cout << " ";
		}
		cout << qq.front()->value;
		if(qq.front()->left!=NULL){
			qq.push(qq.front()->left);
		}
		if(qq.front()->right!=NULL){
			qq.push(qq.front()->right);
		}
		qq.pop();
	}

	system("pause");
	return 0;
}


發佈了99 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章