1064. Complete Binary Search Tree

題目鏈接:http://pat.zju.edu.cn/contests/pat-a-practise/1064

按正常思路,重點仍在建樹,需要結合完全二叉樹與二叉搜索樹的性質,確定跟節點的位置。

另外,其他思路見代碼註釋。

/* 
 * 參考:http://biaobiaoqi.me/blog/2013/08/31/pat-1061-pat-1064/
 * 
 * 使用數組存放完全二叉樹,n的做孩子爲2n,右孩子爲2n+1.
 * 對輸入序列排序;
 * 中序遍歷完全二叉樹,訪問節點時插入數據;
 * 按序訪問數組(完全二叉樹的層次遍歷),輸出結果。
 */

#include <stdio.h>
#include <algorithm>

#define SIZE 1000+10

using namespace std;

int buf[SIZE];
int tree[SIZE];
int num=1, n;

void inorder(int cur)
{
	if (2*cur <= n)	{
		inorder(2*cur);
	}
	tree[cur] = buf[num++];
	if (2*cur+1 <= n) {
		inorder(2*cur+1);
	}
}

int main()
{
	scanf ("%d", &n);
	int i;
	for (i = 1; i <= n; i++) {
		scanf ("%d", &buf[i]);
	}

	sort(buf+1, buf+n+1);

	// 中序遍歷時插入數據
	inorder(1);
	for (i = 1; i < n; i++) {
		printf ("%d ", tree[i]);
	}
	printf ("%d\n", tree[i]);

	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章