二叉排序树的生成和插入,诚心100分求救,懂c数据结构二叉树的进
#include <stdlib.h>#include <stdio.h>#include <string.h>#include <math.h>typedef int DataType;typedef struct Node { DataType key; struct Node *lchild, *rchild;}BSTNode;typedef BSTNode *BSTree;void insert(BSTree *T , DataType key){ BSTNode *f,*p = *T; while ( p != NULL ){ /*不为空则寻找插入点*/ if ( p->key == key ) return; f = p ; p = key < p->key ? f->lchild : f->rchild ; } /*插入*/ p = (BSTNode*)malloc(sizeof(BSTNode)); p->key = key; if( *T == NULL ){ *T = p ; }else{ if (key < f->key){ f->lchild = p; }else { f->rchild = p; } }}/*显示右子树,也就是显示最右边一斜线那些最右分支*/void right_show(BSTree *T){ BSTNode *p = *T ; printf("%d",(*T)->key); while( p != NULL ){ p = p->rchild; printf("%d",p->key); }}void main(){ int i = 1 ; BSTree T = NULL ; printf("start"); /*简单地形成单条右子树,这么简单还是插入有误,什么情况呀,求救 ,救命啊!!!*/ for(i = 1 ; i<=10 ; i++ ){ insert(&T ,i); } right_show(&T);} /*插入*/ p = (BSTNode*)malloc(sizeof(BSTNode)); p->key = key; /* >>>> 还有两个指针没有初始化 */ p->lchild = p->rchild = NULL; if( *T == NULL ){ ....
[解决办法]
估计还是初始化的问题。插入节点后,该节点的左右子节点没初始化,下次插入时,在这个节点下面的话,判断whi(p!=NULL)时,可能出错。