原題鏈接:https://pta.patest.cn/pta/test/1342/exam/4/question/20493
浙大oj:1064題
輸入題意:輸入一組數,根據這組數構造一個二叉排序樹而且是完全二叉樹。輸出這個樹的層次遍歷序列。
解題思路:
先把輸入的序列排序得到num[]數組,然後構造一個普通的n個節點的完全二叉樹,節點值可以隨意輸入,之後利用中序遍歷將num[]數組中的值一次填入,利用了二叉排序樹的中序遍歷序列是遞增序列的性質。
源代碼:
# include <stdio.h>
# include <algorithm>
# define MAX 1010
using namespace std;
typedef struct Node{
struct Node *l;
struct Node *r;
int data;
}*BiTree,Node;
int num[MAX];
BiTree q[MAX]; //層次遍歷隊列
int co = 0; //中序遍歷填數標記
//遞歸中序遍歷
void InOrder(BiTree T){
if(T!=NULL){
InOrder(T->l);
T->data = num[co++];
InOrder(T->r);
}
}
/*
解題思路:
先層次遍歷構造一個二叉鏈表存儲的完全二叉樹
在中序遍歷填入相關數據
最後層次遍歷輸出
*/
int main(){
//預處理
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&num[i]);
}
sort(num,num+n);
//層次遍歷建完全二叉樹
BiTree p,T;
//初始化根節點
T = (BiTree) malloc(sizeof(Node));
T->data=1;
T->l = T->r = NULL;
int count = 1,front =0,rear = 1;
q[0] = T; //初始化隊列
while(count <n && front < rear){
p = q[front++];
if(p->l == NULL){
BiTree temp;
temp = (BiTree)malloc(sizeof(Node));
temp -> l = temp -> r = NULL;
temp -> data = count+1; //數據填入什麼都可以,之後還要重新填入
p->l = temp; q[rear++] = temp;
count++;
if(count >= n) break;
}
if(p->r == NULL){
BiTree temp;
temp = (BiTree)malloc(sizeof(Node));
temp->l = temp->r = NULL;
temp ->data = count+1;
p->r = temp; q[rear++] = temp;
count++;
if(count >= n) break;
}
}
//中序遍歷填入數據
InOrder(T);
//層次遍歷輸出結果
front = 0; rear = 1;
q[0] = T;
int flag = 0; //輸出格式控制
while(front < rear){
p = q[front++];
if(p->l!=NULL)
q[rear++] = p->l;
if(p->r!=NULL)
q[rear++] = p->r;
if(flag)
printf(" ");
flag++;
printf("%d",p->data);
}
printf("\n");
return 0;
}