#include<iostream> #include<stdlib.h> #define MAXSIZE 100 using namespace std; typedef struct Node{ char data; struct Node *LChild; struct Node *RChild; }BiNode,*BiTree; typedef struct SNode{ BiTree elem[MAXSIZE]; int top; }SeqStack; void InitStack(SeqStack*S){ S->top==-1; } int Push(SeqStack *S,BiTree &p){ if(S->top==MAXSIZE-1){ cout<<"栈满" ; return 1; } else{ S->elem[++S->top]=p; return 0; } } int Pop(SeqStack *S,BiTree &p){ if(S->top==-1){ cout<<"栈空"; return 1; } else{ p=S->elem[S->top]; S->top--; return 0; } }BiTree CreateTree(){ BiTree root; char ch; scanf("%c",&ch); if(ch=='#'){ return NULL; }else{ root=(BiTree)malloc(sizeof(BiNode)); if(root==NULL){ cout<<"创建失败"; return NULL; }root->data=ch; root->LChild=CreateTree(); root->RChild=CreateTree(); return root; } }void PreOrder2 (BiTree T){ BiTree p=T; SeqStack s; InitStack(&s); while(p!=NULL) {cout<<p->data;//访问当前节点 Push(&s,p); if(p->LChild!=NULL){ p=p->LChild; } else if(s.top!=-1) { while(s.top!=-1){ Pop(&s,p); p=p->RChild; if(p!=NULL)break; } } else p=NULL;//无后继 } } int main(){ BiTree T=CreateTree(); PreOrder2(T);cout<<endl; return 0; }为什么输出不全
时间: 2024-01-15 12:02:29 浏览: 28
经过分析,程序的问题在于在 `InitStack` 函数中没有正确初始化栈顶指针 `top`,应该使用赋值运算符 `=` 而不是比较运算符 `==`。正确的代码如下:
```
void InitStack(SeqStack *S) {
S->top = -1; // 使用赋值运算符初始化栈顶指针
}
```
此外,程序还存在一个潜在的问题,即当输入的表达式中包含空格或其他非法字符时,程序会陷入死循环,因此需要对输入进行处理,只读取有效的字符,忽略空格和其他非法字符。可以使用 `cin.get()` 替换 `scanf("%c",&ch)` 来实现这一功能,代码如下:
```
char ch;
cin.get(ch);
while (ch == ' ' || ch == '\n' || ch == '\r') { // 忽略空格和其他非法字符
cin.get(ch);
}
if (ch == '#') {
return NULL;
} else {
BiTree root = (BiTree)malloc(sizeof(BiNode));
if (root == NULL) {
cout << "创建失败";
return NULL;
}
root->data = ch;
root->LChild = CreateTree();
root->RChild = CreateTree();
return root;
}
```
经过上述修改,程序应该就可以正确输出了。