二叉排序树插入的非递归算法,,高分求助!!!请大家指点错误!!!
#include <stdio.h>
#include <stdlib.h>
#define ENDKEY 0
typedef int KeyType;
typedef struct node
{
KeyType key ;
struct node *lchild,*rchild;
}BSTNode, *BSTree;
int InsertBST(BSTree *bst, KeyType K)
{
BSTree q, s;
s=(BSTree)malloc(sizeof(BSTNode));
s->key=K;
s->lchild = NULL;
s->rchild = NULL;
if ( *bst == NULL )
{
*bst = s;
return 1;
}
q = *bst;
while(q)
{
if(K==q->key) return 0;
if(K<q->key) q = q->lchild;
else q = q->rchild;
}
q = s;
return 1;
}
void CreateBST(BSTree *bst)
{
KeyType key;
*bst=NULL;
scanf("%d", &key);
while (key!=ENDKEY)
{
InsertBST(bst, key);
scanf("%d", &key);
}
}
void PreOrder(BSTree root)
{
if (root!=NULL)
{
printf("%d ",root->key);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void main()
{
BSTree T;
printf("建立二叉排序树,请输入序列:\n");
CreateBST(&T);
printf("先序遍历输出序列为:");
PreOrder(T);
}
[解决办法]
a=5;b=a;然后改b=10,a还是5吧,你的想法应该是用指针BSTree *q才行,代码类似...
BSTree *q, s;... q = bst; while (*q) { if (K==(*q)->key) { free(s); return 0; } if (K<(*q)->key) q = &(*q)->lchild; else q = &(*q)->rchild; } *q = s;