二叉排序树问题
程序代码:
#include <stdio.h> #include <malloc.h> typedef struct node { int key; struct node *lchild, *rchild; }*bilist, binode; bilist Insert (bilist t, binode *s) { binode *p, *q; if (t==NULL) return s; p = t; while (p!=NULL) { q = p; //q结点为p结点的双亲 if (s->key==p->key) return t; else if (s->key > p->key) p = p->rchild; else p = p->lchild; } if (s->key > q->key) q->rchild = s; else q->lchild = s; return t; } bilist CreateBST (bilist t) { binode *s; int i, n; int key; t = NULL; printf ("结点数:"); scanf ("%d", &n); printf ("输入%d个结点的编号:", n); for (i=1; i<=n; i++) { scanf ("%d", &key); s = (binode*) malloc (sizeof(binode)); s->lchild = NULL; s->rchild = NULL; s->key = key; t = Insert (t, s); } return t; } void InorderBST (bilist t) { binode *s; s = t; if (s!=NULL) { InorderBST (s->lchild); printf ("%d ", s->key); InorderBST (s->rchild); } } void InsertBST (bilist t, int k) { binode *p, *f; p = t; while (p) { if (p->key==k) return; f = p; p = (k < p->key) ? p->lchild : p->rchild; } p = (binode*) malloc (sizeof(binode)); p->key = k; p->lchild = p->rchild = NULL; if (t==NULL) //若t为空则直接插入 t = p; else if (k < f->key) f->lchild = p; else f->rchild = p; } void FreeBST (bilist t) { if (t->lchild) FreeBST (t->lchild); if (t->rchild) FreeBST (t->rchild); free (t); } void main () { int pa, i; char ch; bilist T; T = CreateBST (T); printf ("二叉查找树的中序遍历为:"); InorderBST (T); printf ("\n"); printf ("是否插入关键字?(Y/N)"); ch = getchar (); //这句运行不了 while (ch=='Y' || ch=='y') { printf ("请输入关键字:"); scanf ("%d", &pa); InsertBST (T, pa); printf ("是否继续插入关键字?(Y/N)"); ch = getchar (); } printf ("新二叉查找树的中序遍历为:"); InorderBST (T); printf ("\n"); FreeBST (T); }各位大神们,请问为什么以下这段代码运行不了?
我是想实现动态插入结点的,就是随意增加结点个数,直到输入N时结束增加结点
ch = getchar ();
while (ch=='Y' || ch=='y')
{
printf ("请输入关键字:");
scanf ("%d", &pa);
InsertBST (T, pa);
printf ("是否继续插入关键字?(Y/N)");
ch = getchar ();
}