USTC機試—//算法求解:根據文件中的先序序列創建一棵樹然後中序輸出深度小於depth/2的結點,其中零代表葉子結點,depth就是遍歷樹的深度

註解:此題比較綜合,設計根據先序序列建立一顆樹,然後用遞歸確定樹的高度,然後再保存到depth/2的高度的樹,最後用中序遍歷輸出即可,即牽涉到四個算法。
輸入文件3.in如下:

ABC00DE0000
輸出文件3.out如下:

BA
代碼如下:

//算法求解:根據文件中的先序序列創建一棵樹然後中序輸出深度小於depth/2的結點,其中零代表葉子結點,depth就是遍歷樹的深度
#include<stdio.h>
#include<queue>
using namespace std;
#define N 100
struct Node{
  Node *lchild;
  Node *rchild;
  char c;
}E[N];
int loc;
char s[N];
Node *create(){//靜態分配一個結點方法
     E[loc].lchild=E[loc].rchild=NULL;
	 return &E[loc++];
}
int i=0;
Node *preCreate(char s[]){//先序建立一顆樹
	if(s[i]=='\0'||s[i]=='0')return NULL;//如果到結尾或者是遇到葉子結點返回空
    Node *p=create();
	p->c=s[i++];
	p->lchild=preCreate(s);
    p->rchild=preCreate(s);
	return p;
}
int depth(Node *T){//遞歸確定樹的高度
    if(T==NULL)return 0;
	int left=1;
	int right=1;
    left+=depth(T->lchild);
	right+=depth(T->rchild);
	return left>right?left:right;
}
void depthCreate(Node *p,int depth){//保存新的高度爲depth的樹
	if(p!=NULL){
		if(depth==0){p->lchild=p->rchild=NULL;}
		else{depthCreate(p->lchild,depth-1);depthCreate(p->rchild,depth-1);}
	}else
		return;
}
FILE *fp1,*fp2;
void inOrder(Node *p){//中序遍歷輸出一棵樹的內容
	if(p->lchild!=NULL)inOrder(p->lchild);
	fprintf(fp2,"%c",p->c);
    if(p->rchild!=NULL)inOrder(p->rchild);
}
int main(){
fp1=fopen("3.in","r");
fp2=fopen("3.out","w");
fscanf(fp1,"%s",s);
Node *p=preCreate(s);
int len=depth(p);
depthCreate(p,len/2);
inOrder(p);
fclose(fp1);
fclose(fp2);//ps爲啥我老是忘記這個。。。
return 0;
}




















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