请教一个关于二叉树创建与访问的问题,测试访问的时候出现内存段错误
代码如下:
#include <stdio.h>#include <stdlib.h>typedef struct node * treePtr;struct node{ int data; treePtr lch,rch;};void createTree(treePtr T){ T = (treePtr)malloc(sizeof(struct node)); if(T) { printf("Enter the data: "); scanf("%d",&(T->data)); if(T->data == 0) { free(T); T = NULL; return; } // printf("Data: %d\n",T->data); createTree(T->lch); createTree(T->rch); } else { T = NULL; }}int main(){ treePtr T; createTree(T); printf("%d\n",T->data); return 0;}#include <stdlib.h>#include <stdio.h>#include <string.h>#define NULL 0typedef struct tree{ char Data; struct tree *left,*right;}*Bitree;Bitree create(Bitree T){ char ch; scanf("%c",&ch); if(ch=='#')//输入#号表示空 { T=NULL; } else { if(!(T=(Bitree )malloc(sizeof(Bitree)))) { printf("错误!\n"); } T->Data=ch; T->left=create(T->left); T->right=create(T->right);}return T;}void xianxu(Bitree T){ if(T) { printf("%c",T->Data); xianxu(T->left); xianxu(T->right); }}void zhongxu(Bitree T){ if(T) { zhongxu(T->left); printf("%c",T->Data); zhongxu(T->right); }}void houxu(Bitree T){ if(T) { houxu(T->left); houxu(T->right); printf("%c",T->Data); }}void main(){Bitree T;T=create(T);xianxu(T);printf("\n");zhongxu(T);printf("\n");houxu(T);printf("\n");}非递归先中后的遍历算法C/C++ code//1.先序遍历非递归算法#define maxsize 100typedef struct{ Bitree Elem[maxsize]; int top;}SqStack;void PreOrderUnrec(Bitree t){ SqStack s; StackInit(s); p=t; while (p!=null || !StackEmpty(s)) { while (p!=null) //遍历左子树 { visite(p->data); push(s,p); p=p->lchild; }//endwhile if (!StackEmpty(s)) //通过下一次循环中的内嵌while实现右子树遍历 { p=pop(s); p=p->rchild; }//endif }//endwhile }//PreOrderUnrec//2.中序遍历非递归算法#define maxsize 100typedef struct{ Bitree Elem[maxsize]; int top;}SqStack;void InOrderUnrec(Bitree t){ SqStack s; StackInit(s); p=t; while (p!=null || !StackEmpty(s)) { while (p!=null) //遍历左子树 { push(s,p); p=p->lchild; }//endwhile if (!StackEmpty(s)) { p=pop(s); visite(p->data); //访问根结点 p=p->rchild; //通过下一次循环实现右子树遍历 }//endif }//endwhile}//InOrderUnrec//3.后序遍历非递归算法#define maxsize 100typedef enum{L,R} tagtype;typedef struct { Bitree ptr; tagtype tag;}stacknode;typedef struct{ stacknode Elem[maxsize]; int top;}SqStack;void PostOrderUnrec(Bitree t){ SqStack s; stacknode x; StackInit(s); p=t; do { while (p!=null) //遍历左子树 { x.ptr = p; x.tag = L; //标记为左子树 push(s,x); p=p->lchild; } while (!StackEmpty(s) && s.Elem[s.top].tag==R) { x = pop(s); p = x.ptr; visite(p->data); //tag为R,表示右子树访问完毕,故访问根结点 } if (!StackEmpty(s)) { s.Elem[s.top].tag =R; //遍历右子树 p=s.Elem[s.top].ptr->rchild; } }while (!StackEmpty(s));}//PostOrderUnrec