二叉树问题急解决立即给分!!
redez 2004-12-18 09:19:30 我现在出现的问题是
用先序非递归方法遍历二叉树时输入的结果正好比正常的多了48不知道为什么
用栈作的
还有就是怎么在屏幕上缩格打印二叉树呢
#include "malloc.h"
#include "stdio.h"
#define ERROR 0
#define OVERFLOW -2
#define OK 1
typedef char TElemType;
typedef int Status;
typedef struct BiTNode
{
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
struct Stack
{
BiTree ds;
Stack *next;
};
Stack *Push(Stack *top, BiTree ds)
{
Stack *t = top;
top = (Stack *) malloc (sizeof(Stack));
top->ds=ds;
top->next = t;
return top;
}
Stack *Pop(Stack *top)
{
if (top){
Stack *t = top;
top = top->next;
free(t);
} else
;//Pop error message...
return top;
}
BiTNode *GetTop(Stack *top)
{
if (top)
return top->ds;
else
return NULL;
}
void PreorderNoDigui(BiTree T)
{
BiTree p;
Stack *top = NULL;
top = Push(top, T);
printf("%d ", top->ds->data);
p = T->lchild;
while (1){
for (; p; p = p->lchild){
printf("%d ", p->data);
top = Push(top, p);
}
do
if (top)
{
p = GetTop(top);
p = p->rchild;
top = Pop(top);
} else
return;
while (!p);
}
}
Status CreateBiTree(BiTree &T)
{
char ch;
scanf("%c",&ch);
if(ch=='#')
T=NULL;
else
{
if(!(T=(BiTNode *) malloc (sizeof (BiTNode))))
return (OVERFLOW);
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
return OK;
}
void main()
{
BiTree T;
printf("请输入二叉树\n");
CreateBiTree(T);
printf("\n");
printf("\n非递归先序遍历为:\n");
PreorderNoDigui(T);
printf("\n");
getchar();
}