Question description: I want to output a binary tree as post order, but the program occurred in a runtime error. I don't know where the problem occurred. And I don't know how to solve it everytime I occurred in runtime error, unlike compile error. By the way, what books or articles should I read about solving runtime error?
MainFunc.c
#include "AllFun.h"
int main(int argc, char* argv[])
{
BiTree T;
T = create();
/* Traverse nonrecursively binary tree as post order */
PostOrder(T);
return 0;
}
AllFun.h
#include <stddef.h> // NULL
#include <stdlib.h> //malloc()
#include <stdio.h>
#define MaxSize 10
typedef int ElemType;
typedef struct BiTNode {
ElemType data;
struct BiTNode* lchild, * rchild;
} BiTNode, * BiTree;
typedef struct Stack {
ElemType data[MaxSize];
int top;
} SqStack;
BiTree create();
void PostOrder(BiTree T);
OtheFunc.c
#include "AllFun.h"
BiTree newNode(int value)
{
BiTree T = (BiTNode*)malloc(sizeof(BiTNode));
if (T) {
T->data = value;
T->lchild = T->rchild = NULL;
}
return T;
}
void insert(BiTree* T, int x)
{
if (*T == NULL) {
*T = newNode(x);
return;
}
if (x < (*T)->data) {
insert(&(*T)->lchild, x);
}
else {
insert(&(*T)->rchild, x);
}
}
BiTree create()
{
ElemType nums[MaxSize];
for (int i = 0; i < MaxSize; ++i) {
nums[i] = ' ';
}
BiTree T = NULL;
printf("Enter value of node to create a binary search tree: ");
for (int i = 0; i < MaxSize; ++i) {
scanf_s("%d", &nums[i]);
insert(&T, nums[i]);
}
return T;
}
void init(SqStack *s)
{
s->top = -1;
}
int isEmpty(SqStack *s)
{
int ret = 0;
if (s->top == -1) {
ret = 1;
}
return ret;
}
void push(SqStack *s, BiTree p)
{
if (s->top == MaxSize - 1) {
printf("stack is full\n");
}
else {
s->data[++s->top] = p->data;
}
}
void getTop(SqStack *s, BiTree p)
{
if (s->top == -1) {
printf("stack is empty\n");
return;
}
p->data = s->data[s->top];
}
void pop(SqStack *s, BiTree p)
{
if (s->top == -1) {
printf("stack is empty\n");
}
p->data = s->data[s->top--];
}
void PostOrder(BiTree T)
{
BiTree p = T, r = NULL;
SqStack s;
init(&s);
while (p || !isEmpty(&s)) {
if (p) {
push(&s, p);
p = p->lchild;
}
else {
getTop(&s, p);
if (p) {
if (p->rchild && p->rchild != r) {
p = p->rchild;
push(&s, p);
p = p->lchild;
}
}
else {
pop(&s, p);
if (p) {
printf("%d ", p->data);
}
r = p;
p = NULL;
}
}
}// while
}