| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
二叉链表的存储结构建树时要用指针的指针,本地调试的时候发现了这个问题http://blog.163.com/beachman_cy/blog/static/249496019201511229338503/
Problems: Falling Leaves
Description: 现在有一颗二叉排序树,让他的叶子一层一层脱落,然后让你恢复这颗二叉排序树!输出它的前序遍历序列!
Solution: 首先要恢复这颗排序二叉树,注意,它是一层一层脱落的,那么我们倒过来建立这颗二叉排序树,就是一个一个往二叉排序树中插入元素,开始的时候我没看清楚是一颗排序树,所以觉得无从下手,既然是二叉排序树那么很好做了,就是教科书上建立二叉排序树的过程,注意一下,建立二叉排序树时,要用指针的指针,因为你是要为指针赋值,而不是用指针来引用元素!
Code(C++):
#include <stdio.h>
#include <string.h>
#include <malloc.h>
const int _MAXN=1000;
typedef struct tagTree{
tagTree *right,*left;
char character;
}Tree;
char string[_MAXN];
Tree *root;
void insertTree(Tree **p,char c){
if((*p)==NULL){
(*p)=(Tree *)malloc(sizeof(Tree));
(*p)->left=NULL;
(*p)->right=NULL;
(*p)->character=c;
return ;
}
if(c<(*p)->character){
insertTree(&(*p)->left,c);
}else{
insertTree(&(*p)->right,c);
}
}
void print(Tree *p){
if(p!=NULL){
printf("%c",p->character);
print(p->left);
print(p->right);
}
}
int main(){
char tmpString[100];
while(true){
//initialize
memset(string,0,sizeof(string));
while(scanf("%s",tmpString),tmpString[0]!='*'&&tmpString[0]!='$'){
strcat(string,tmpString);
}
int len=strlen(string);
root=NULL;
for(int i=len-1;i>=0;i--){
insertTree(&root,string[i]);
}
//print
print(root);
puts("");
if(tmpString[0]=='$'){
break;
}
}
return 0;
}
得交C++,G++ CompileError,说没有malloc.h这个文件,也是醉了
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator