关于非递归创建二叉树在网上也看到了各种各样的算法,但是不知道为什么,每个算法我几乎是照搬到vs都没办法正常运行,每次都提示指针为空导致无法运行,所以想请教一下,究竟哪边有问题?
下附代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
char data;
struct node* lchild, * rchild;
}tree;
void inorder(tree* t)
{
tree* s[100];
int top = 0;
tree* p = t;
while (p != NULL || top != 0)
{
while (t)
{
s[++top] = p; p = p->lchild;
}
if (top)
{
p = s[top--];
if (p->data != ' ')
printf("%c ", p->data);
p = p->rchild;
}
}
}
void create_tree(tree* t,char*str)
{
tree* s[100];
tree* p = NULL;
int top, k, j; char ch;
top = 0; j = 0; k = 0;
t = NULL;
ch = str[j];
while (ch != '\0')
{
switch (ch)
{
case'(':top++; s[top] = p; k = 1; break;
case')':top--; break;
case',':k = 2; break;
default:
p = (tree*)malloc(sizeof(tree));
p->data = ch; p->lchild = p->rchild = NULL;
printf("%c", p->data);
if (t == NULL)
t = p;
else
{
switch(k)
{
case 1:s[top]->lchild = p; break;
case 2:s[top]->rchild = p; break;
}
}
}
ch = str[++j];
}
}
void main()
{
tree* t;
t = (tree*)malloc(sizeof(tree));
char str[100];
printf("请创建二叉树:\n");
scanf("%s", &str);
create_tree(t,str);
printf("%c", t->data);
printf("\n二叉树的中序遍历输出为:");
inorder(t);
}
case的括号是啥