二叉树
Question one
#include "bintree.h"
char *a="ABC##D#E##F##";
void preorder1(bintree t)
{
seqstack s;
s.top = 0;
while(t || s.top != 0)
{
if(t)
{
push(&s, t);
printf("%c", t->data);
t = t->lchild;
}
else
{
t = pop(&s);
t = t->rchild;
}
}
}
int main()
{ bintree t;
t=creatbintree();
printf("二叉树的前序序列为:\n");
preorder1(t);
return 0;
}
Question two
#include "bintree.h"
char *a="ABC##D#E##F##";
void levelbintree(bintree t)
{
bintree queue[N];
int head = 0, end = 1;
queue[head] = t;
while(head < end)
{
if(queue[head]->lchild) queue[end++] = queue[head]->lchild;
if(queue[head]->rchild) queue[end++] = queue[head]->rchild;
printf("%c",queue[head++]->data);
}
return;
}
int main()
{ bintree t;
t=creatbintree();
printf("二叉树的层次序列为:\n");
levelbintree(t);
return 0;
}
Question three
#include "bintree.h"
char *a="ABC##D##EF#G###";
bintree prelast(bintree t)
{
if(t == NULL) return NULL;
else
{
if(t->lchild == NULL && t->rchild == NULL)
return t;
else
{
if(t->rchild) return prelast(t->rchild);
else return prelast(t->lchild);
}
}
}
bintree prelast_2(bintree t)
{
bintree s = t;
if(s)
{
while(s->lchild || s->rchild)
{
if(s->rchild) s = s->rchild;
else s = s->lchild;
}
}
return s;
}
bintree postfirst(bintree t)
{
bintree s = t;
if(s)
{
while(s->lchild || s->rchild)
{
if(s->lchild) s = s->lchild;
else s = s->rchild;
}
}
return s;
}
int main()
{ bintree t,p,q;
t=creatbintree();
p=prelast(t);
q=postfirst(t);
if (t!=NULL)
{ printf("前序遍历最后一个结点为:%c\n",p->data);
printf("后序遍历第一个结点为:%c\n",q->data);
}
else printf("二叉树为空!");
return 0;
}
Question four
#include "bintree.h"
char *a="ABC##D##EF#G###";
int Depth(bintree t,char x)
{
int m, n;
if(!t) return -1;
if(t->data == x) return 1;
m = Depth(t->lchild, x);
if(m != -1) return m + 1;
else
{
n = Depth(t->rchild, x);
if(n != -1) return n + 1;
else return -1;
}
}
int main()
{ bintree root;
char x;
int k=0;
root=creatbintree();
printf("请输入树中的1个结点值:\n");
scanf("%c",&x);
k=Depth(root,x);
printf("%c结点的层次为%d\n",x,k);
}
Question five
#include "bintree.h"
char *a="ABC##D##EF#G###";
void change(bintree t)
{
bintree temp;
if(t)
{
temp = t->lchild;
t->lchild = t->rchild;
t->rchild = temp;
if(t->lchild) change(t->lchild);
if(t->rchild) change(t->rchild);
}
}
int main()
{ bintree root;
root=creatbintree();
change(root);
preorder(root);
}
Question six
#include "bintree.h"
#include <string.h>
char *a="";
bintree buildBintree(char *pre, char *mid,int length)
{
if(length)
{
bintree root = (bintree)malloc(sizeof(binnode));
root->data = pre[0];
int i;
for(i=0;mid[i] != pre[0];i++);
mid[i] = '\0';
root->lchild = buildBintree(pre+1,mid,i);
root->rchild = buildBintree(pre+i+1,mid+i+1,length-i-1);
return root;
}
else return NULL;
}
int main()
{ bintree root;
char pre[100],mid[100];
puts("请输入前序序列:");
gets(pre);
puts("请输入中序序列:");
gets(mid);
root=buildBintree(pre,mid,strlen(pre));
puts("后序序列是:");
postorder(root);
}