拾不到一片光 2016-05-22 07:52 采纳率: 0%
浏览 1257

求大神看看,C语言二叉树非递归遍历问题 ,最后输出正确,然后在程序崩溃

#include
#include
#include

typedef struct TNode {
char date;
struct TNode *lchild,*rchild;
}TNode,*BiTree;

typedef struct {
BiTree top;
BiTree *base;
int stacksize;
}Stack;
int createBiTree(BiTree &S){
char ch;
scanf("%c",&ch);
if(ch=='#') S=NULL;
else {
S=(TNode *)malloc(sizeof(TNode));
if(!S)
exit(0);
S->date=ch;
createBiTree(S->lchild);
createBiTree(S->rchild);
}
return 1;
}
int Initstack(Stack &R) {
R.base=(BiTree *)malloc(100*sizeof(TNode
));
if(!R.base) exit(0);
R.top=R.base;
R.stacksize=100;
return 1;
}
void push(Stack &R,BiTree e) {
if(!(R.top-R.base)) {
R.base=(BiTree )realloc(R.base,(R.stacksize+10)*sizeof(TNode *));
R.top=R.stacksize+R.base;
R.stacksize+=10;
}
*R.top++=e;
}
void pop(Stack &R,BiTree &e) {
if(R.top-R.base==0) return ;
e=
(--R.top);
// return e;
}
void printBiTree(BiTree S) {
Stack R;
BiTree p;
if(!S) return ;
else {
Initstack(R);
p=S;
while(p || (R.top-R.base))
{
while(p) {
// printf("%3c",p->date);
push(R,p);

p=p->lchild;
}//while

        if(!(R.top-R.base))  return ;
        else
        {
            pop(R,p);
            printf("%3c",p->date);
            p=p->rchild;
        }
    }

// return 1;

}

// free(R);
}

int other(BiTree S)
{
if(!S)
return 0;
else
{
printf("%c",S->date);
other(S->lchild);
other(S->rchild);
}
return 1;
}
int main() {
BiTree S;
createBiTree(S);
printBiTree(S);
return 0;
// free(R);
free(S);
}

先序遍历输出,#代表空

  • 写回答

2条回答 默认 最新

  • lbcab 2016-05-22 08:04
    关注

    将free(S) 放在 renturn 0; 前面
    因为 return 0;后程序退出, 不会调用free(S) 去释放内存

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog