二叉树的问题
(2)已知二叉树后序遍历序列是dabec,中序遍历序列是debac,它的前序遍历序列是A)acbedB)decabC)deabcD)cedba求详细解析,一定要详细...
(2) 已知二叉树后序遍历序列是dabec,中序遍历序列是debac,它的前序遍历序列是
A) acbed
B) decab
C) deabc
D) cedba
求详细解析,一定要详细 展开
A) acbed
B) decab
C) deabc
D) cedba
求详细解析,一定要详细 展开
展开全部
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct tree
{
char info;
struct tree *left;
struct tree *right;
};
struct tree *root; /*树的第一个结点*/
struct tree *construct(struct tree *root, struct tree *r, char info);
void print(struct tree *r, int l);
int main(void)
{
char s[80];
root = NULL;
do
{
printf("Please input a character:");
gets(s);
root = construct(root,root,*s);
}while(*s);
print(root,0);
getch();
return 0;
}
struct tree *construct(
struct tree *root,
struct tree *r,
char info)
{
if(!r)
{
r = (struct tree *)malloc(sizeof(struct tree));
if(!r)
{
printf("内存分配失败!");
exit(0);
}
r->left = NULL;
r->right = NULL;
r->info = info;
if(!root)
return r;
if(info < root->info)
root->left = r;
else
root->right = r;
return r; /*是return r;还是return root;*/
}
if(info < r->info)
construct(r,r->left,info);
else
construct(r,r->right,info);
return root;
}
void print(struct tree *r, int l)
{
int i;
if(!r)
return;
print(r->left,l+1);
for(i = 0;i < l;++i)
printf(" ");
printf("%c\n",r->info);
print(r->right,l+1);
}
上面的是采用中序遍历,采用前序遍历和后序遍历的函数如下:
void scan(struct tree root)(前序遍历)
{
if(!root)return;
if(root->info);
执行相应操作;
scan(root->left);
scan(root->right);
}
void scan(struct tree root)(后序遍历)
{
if(!root)return;
scan(root->left);
scan(root->right);
if(root->info);
执行相应操作;
}
#include <stdlib.h>
#include <conio.h>
struct tree
{
char info;
struct tree *left;
struct tree *right;
};
struct tree *root; /*树的第一个结点*/
struct tree *construct(struct tree *root, struct tree *r, char info);
void print(struct tree *r, int l);
int main(void)
{
char s[80];
root = NULL;
do
{
printf("Please input a character:");
gets(s);
root = construct(root,root,*s);
}while(*s);
print(root,0);
getch();
return 0;
}
struct tree *construct(
struct tree *root,
struct tree *r,
char info)
{
if(!r)
{
r = (struct tree *)malloc(sizeof(struct tree));
if(!r)
{
printf("内存分配失败!");
exit(0);
}
r->left = NULL;
r->right = NULL;
r->info = info;
if(!root)
return r;
if(info < root->info)
root->left = r;
else
root->right = r;
return r; /*是return r;还是return root;*/
}
if(info < r->info)
construct(r,r->left,info);
else
construct(r,r->right,info);
return root;
}
void print(struct tree *r, int l)
{
int i;
if(!r)
return;
print(r->left,l+1);
for(i = 0;i < l;++i)
printf(" ");
printf("%c\n",r->info);
print(r->right,l+1);
}
上面的是采用中序遍历,采用前序遍历和后序遍历的函数如下:
void scan(struct tree root)(前序遍历)
{
if(!root)return;
if(root->info);
执行相应操作;
scan(root->left);
scan(root->right);
}
void scan(struct tree root)(后序遍历)
{
if(!root)return;
scan(root->left);
scan(root->right);
if(root->info);
执行相应操作;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询