用C++实现二叉树的建立和遍历中遇到的问题
遍历结果有问题,中序遍历是按照严蔚敏书上的算法实现,先序是自己写的,运行结果不对,在主程序里加了输出,结果发现先序遍历后根结点指针root的值在先序遍历后改变了,但程序中...
遍历结果有问题,中序遍历是按照严蔚敏书上的算法实现,先序是自己写的,运行结果不对,在主程序里加了输出,结果发现先序遍历后根结点指针root的值在先序遍历后改变了,但程序中并没有给他赋值,这是为什么呢,怎样修改才对?
#include <stdio.h>
#define MAXSIZE 200
typedef struct node
{
char data;
struct node *lchild, *rchild;
}BTNode;
BTNode* CreatBitTree()
{
char ch;
BTNode *b;
scanf("%c",&ch);
if (ch == '#')
{
b = NULL;
}
else
{
b = (BTNode *)malloc(sizeof(BTNode));
b->data = ch;
b->lchild = CreatBitTree();
b->rchild = CreatBitTree();
}
return b;
}
void PreOrder(BTNode* b)
{
BTNode *stack[MAXSIZE],*p;
int top = 0;
stack[top++]=b;
p=stack[top-1];
while(top>0)
{
while(p)
{
printf("%c ",p->data);
p=p->lchild;
stack[top++]=p;
}
top--;
p=stack[--top];
if(p)
{
p=p->rchild;
stack[top++]=p;
}
}
printf("\n");
}
void InOrder(BTNode* b)
{
BTNode *stack[MAXSIZE],*p;
int top = 0;
stack[top++]=b;
while(top>0)
{
while(stack[top-1])
{
p=stack[top-1];
stack[top++]=p->lchild;
}
top--;
if(top>0)
{
p=stack[--top];
printf("%c ",p->data);
stack[top++]=p->rchild;
}
}
printf("\n");
}
int main()
{
BTNode *root = NULL;
root = CreatBitTree();
printf("%d,%d,%d\n",root,root->lchild,root->rchild);
Prerder(root);
printf("%d,%d,%d\n",root,root->lchild,root->rchild);
InOrder(root);
printf("%d,%d,%d\n",root,root->lchild,root->rchild);
getch();
}
写错标题了,不是c++,是c语言 展开
#include <stdio.h>
#define MAXSIZE 200
typedef struct node
{
char data;
struct node *lchild, *rchild;
}BTNode;
BTNode* CreatBitTree()
{
char ch;
BTNode *b;
scanf("%c",&ch);
if (ch == '#')
{
b = NULL;
}
else
{
b = (BTNode *)malloc(sizeof(BTNode));
b->data = ch;
b->lchild = CreatBitTree();
b->rchild = CreatBitTree();
}
return b;
}
void PreOrder(BTNode* b)
{
BTNode *stack[MAXSIZE],*p;
int top = 0;
stack[top++]=b;
p=stack[top-1];
while(top>0)
{
while(p)
{
printf("%c ",p->data);
p=p->lchild;
stack[top++]=p;
}
top--;
p=stack[--top];
if(p)
{
p=p->rchild;
stack[top++]=p;
}
}
printf("\n");
}
void InOrder(BTNode* b)
{
BTNode *stack[MAXSIZE],*p;
int top = 0;
stack[top++]=b;
while(top>0)
{
while(stack[top-1])
{
p=stack[top-1];
stack[top++]=p->lchild;
}
top--;
if(top>0)
{
p=stack[--top];
printf("%c ",p->data);
stack[top++]=p->rchild;
}
}
printf("\n");
}
int main()
{
BTNode *root = NULL;
root = CreatBitTree();
printf("%d,%d,%d\n",root,root->lchild,root->rchild);
Prerder(root);
printf("%d,%d,%d\n",root,root->lchild,root->rchild);
InOrder(root);
printf("%d,%d,%d\n",root,root->lchild,root->rchild);
getch();
}
写错标题了,不是c++,是c语言 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询