我建立二叉树有什么问题啊
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
//用了一个小时,头脑里面基本上有了思路
//弄明白了队列这种数据结构
using namespace std;
typedef struct QElementType
{
char parent;
char side;
char myself;
}QElementType;
typedef struct QNode{
QElementType data;
struct QNode *next;
//struct QNode *lchild;
//struct QNode *rchild;
}QNOde,*QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
struct BinTree
{
char mydata;
struct BinTree *lchild;
struct BinTree *rchild;
};
//先序遍历二叉树
void PreTree(BinTree* &B,QElementType e)
{
BinTree *t = (BinTree *)malloc(sizeof(BinTree));
t->mydata = e.myself;
if(B == NULL)
return;
if(B->mydata == e.parent)
{
if(e.side == 'L')
{
B->lchild = t;
}
if(e.side == 'R')
{
B->rchild = t;
}
}
PreTree(B ->lchild,e);
PreTree(B ->rchild,e);
}
void PreTree1(BinTree *B)
{
if(B == NULL)
return;
printf("%c",B->mydata);
PreTree1(B->lchild);
PreTree1(B->rchild);
}
void InitQueue(LinkQueue &Q)
{
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if(!Q.front) exit(0);
Q.front-> next = NULL;
return;
}
void EnQueue(LinkQueue &Q,QElementType e)
{
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
if(!p) exit(0);
p->data = e;
p->next = NULL;
Q.rear -> next = p;
Q.rear = p;
}
QElementType GetHead(LinkQueue &Q)
{
QElementType e;
e = Q.front->next->data;
return e;
}
QElementType DeQueue(LinkQueue &Q)
{
QueuePtr p =NULL;
if(Q.front == Q.rear)
exit(0);
p = (QueuePtr)malloc(sizeof(QNode));
p = Q.front -> next;
QElementType e;
e = p -> data;
Q.front->next = p->next;
if(Q.rear == p) Q.rear = Q.front;
free(p);
return e;
}
int main()
{
LinkQueue Q;
InitQueue(Q);
BinTree *B = NULL;
char charray[10];
char ch;
do
{
cout << "Please input three character to discribe children-node:\n";
scanf("%s",charray);
QElementType e;
e.myself = charray[0];
e.parent = charray[1];
e.side = charray[2];
EnQueue(Q,e);
if(e.parent == '#')
B->mydata = e.myself;
else{
cout <<"cdskcvsd";
PreTree(B,e);
}
cout << "Do you want to continue your input?\n";
scanf("%c",&ch);
}while(ch == 'Y');
cout << "woshitiancxai";
PreTree1(B);
return 0;
}
//每个节点都会有三个信息,父节点的数据,自己本身的数据,还有就是它是右子节点还是左子节点,用‘#’表示空,用‘L’或‘R’表示是左还是右,可我一输入第一个节点的信息时,就会程序终止运行!怎么办啊? 二叉树 指针 C
[解决办法]
do
{
cout << "Please input three character to discribe children-node:\n";
scanf("%s",charray);
QElementType e;
e.myself = charray[0];
e.parent = charray[1];
e.side = charray[2];
EnQueue(Q,e);
if(e.parent == '#')
B->mydata = e.myself;
else{
cout <<"cdskcvsd";
PreTree(B,e);
}
cout << "Do you want to continue your input?\n";
scanf("%c",&ch);
}while(ch == 'Y');
嗯,曾经有过这样的问题,原因是scanf函数遇到空白符(回车、tab、空格)即停止本次读输入的操作,但是空白符仍会留在输入流中,所以你上面scanf("%s",charray);之后的操作scanf("%c",&ch);,ch会读到一个空白符,不等于'Y',所以do{}while循环即停止了
解决方法:scanf(" %s",charray); scanf(" %c",&ch);,注意这里百分号前有一个空格!作用是跳过输入流前面的空白符,具体还请lz自己去查一下scanf的用法
[解决办法]
只是一个回车符在缓冲区里,
getchar或者多一次scanf吃掉都是可以的!