帮忙看一下吧!二叉树

unk__ghost 2010-04-30 10:52:27
#include<iostream>
using namespace std;
typedef char Elemtype;
typedef bool status;
typedef struct CTNode{
Elemtype data;
struct CTNode *lchild,*rchild;
}CSNode,*CSTree,*BiTree,*SElemType;

#define max 20
#define mm 10
#define OK 1
#define error 0
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
status InitStack(SqStack &S){
S.base=(SElemType *)malloc(max*sizeof(SElemType));
if(!S.base) return error;
S.top=S.base;
S.stacksize=max;
return OK;
}
status GetTop(SqStack S,SElemType &e){
if(S.top==S.base) return error;
e=*(--S.top);
return OK;
}
status Push(SqStack &S,SElemType e){
if(S.top-S.base>=S.stacksize){
S.base=(SElemType *)realloc(S.base,(max+mm)*sizeof(SElemType));
if(!S.base) return error;
S.top=S.base+S.stacksize;
S.stacksize+=mm;
}
*S.top++=e;
return OK;
}
status Pop(SqStack &S,SElemType &e)
{
if(S.top==S.base) return error;
e=*--S.top;
return OK;
}
status StackEmpty(SqStack &S){
if(S.top==S.base) return 1;
else return 0;
}



class Tree{
private:
CSTree T;

public:
Tree(){
T=NULL;
};
status CreateBiTree();
status InOrderTraverse ();
};

status Tree::CreateBiTree()
{
CSTree p;
Elemtype ch;
SqStack S;
ch=getchar();
InitStack(S);
while(ch!=' '||!StackEmpty(S)){
if(ch!=' '){
p=(CSTree)malloc(sizeof(CSNode));
if(T==NULL) T=p;
if(!p)
return error;
p->data=ch;
Push(S,p);
p=p->lchild;

ch=getchar();
}
else{
p=NULL;
Pop(S,p);
p=p->rchild;
ch=getchar();
}

}
return OK;
}


status Tree::InOrderTraverse()
{
SqStack S;
InitStack(S);
BiTree p=T;
while(p||!StackEmpty(S)){
if(p){
Push(S,p);p=p->lchild;}
else{
Pop(S,p);
cout<<p->data<<endl;
p=p->rchild;
}
}
return OK;
}

int main()
{
Tree T;
T.CreateBiTree();
T.InOrderTraverse();
return 0;
}
...全文
87 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
unk__ghost 2010-05-03
  • 打赏
  • 举报
回复
logiciel 非常感谢你的提醒,一时大意!!非常谢谢!
logiciel 2010-05-01
  • 打赏
  • 举报
回复
CreateBiTree的设计有问题,没有建立起二叉树。可定义一个变量q来保存上次的p,然后再通过q->lchild=p连接2个节点。例如:

CSTree p,q;
。。。
p=(CSTree)malloc(sizeof(CSNode));
if(!p) return error;
p->data=ch;
p->lchild=p->rchild=NULL;
Push(S,p);
if(T==NULL) T=p;
else q->lchild=p;
q=p;


左右节点的处理也需再考虑。
Xiaoloveliuforever 2010-04-30
  • 打赏
  • 举报
回复
看来是CSDN新手啊 不会问问题
unk__ghost 2010-04-30
  • 打赏
  • 举报
回复
估计是内存错误,如果不调试一下的话 肯定不知道,我不是不想,我也不知道怎么错了!!
LHCHC 2010-04-30
  • 打赏
  • 举报
回复
你把问题直接写出来嘛,这样帮忙的人也可以省些时间!
lirg8405 2010-04-30
  • 打赏
  • 举报
回复
直说问题,谁那么有空帮你看啊

64,636

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧