我在 C++ 中有一个二叉树程序,它解析一串字符,然后根据它形成一棵二叉树。我在将参数传输到我的函数时遇到问题。我尝试阅读有关将参数传递给 c 中的函数的教程,并更改了我的代码,但它似乎不起作用。我希望有人帮助我修复参数的传递。
标题:
#define NULL 0
struct TreeEl {
char inf;
struct TreeEl * st, * dr;
};
typedef struct TreeEl root;
root* add(root *r, char st[], int &pos, int &n);
root* create(root *r, char st[100], int n);
void visit(root*);
void preorder(root *r, void visit(root*));
void inorder(root *r, void visit(root*));
void postorder(root *r, void visit(root*));
和代码:
#include "arbore_binar.h"
#include <stdio.h>
using namespace std;
void visit(root *r)
{
printf("Node %c",r->inf);
}
root* add(root *r, char st[], int &pos, int &n)
{
int done=0;
do
{
pos++;
printf(" procesing character:,%c \n",st[pos]);
switch (st[pos])
{
case '(':
{
add(r->st, st, pos, n);
break;
}
case ')':
{
done=1;
break;
}
case ',':
{
add(r->dr, st, pos, n);
break;
}
case '$':
{
if (st[pos+1]==',')
done=1;
if (st[pos+1]==')')
done=1;
break;
}
default:
{
if ((st[pos]>=65)&&(st[pos]<=90))
{
printf(" Added: ,%c \n" ,st[pos]);
root *p;
p = new root;
p->inf=st[pos];
p->st=NULL;
p->dr=NULL;
r=p;
if (st[pos+1]==',')
done=1;
if (st[pos+1]==')')
done=1;
}
else
printf("Error,unknown character: %d ",st[pos]);
}
}
} while ((done==0)&&(pos<n));
return r;
}
root* create(root *r, char st[100], int n)
{
int pos=-1;
root* nod = add(r, st, pos, n);
return nod;
}
void preorder(root *v, void visit(root*))
{
if (v == NULL)
return;
else {
visit(v);
preorder(v->st, visit);
preorder(v->dr, visit);
}
}
void inorder(root *v, void visit(root*))
{
if (v == NULL) return;
else {
inorder(v->st, visit);
visit(v);
inorder(v->dr, visit);
}
}
void postorder(root *v, void visit(root*))
{
if (v == NULL) return;
else {
postorder(v->st, visit);
postorder(v->dr, visit);
visit(v);
}
}
void print(root* x)
{
printf("%c" , x->inf ," " );
}
int main()
{
//char a[100] = "A(B(J,$),C(X,D(E,F($,Y))))";
//char a[100] = "A(B,C(X,D(E,F($,Y))))";
char a[100] = "A(B(C(M,$),D),E(F(X,$),G($,Y)))";
root *r;
r=NULL;
r=create(r, a, 31);
printf("Preorder traversal:" );
preorder(r, print);
printf("\n");
printf("Inorder traversal: ");
inorder(r, print);
printf("\n");
printf("Postorder traversal: ");
postorder
(r,打印);printf("\n");
获取字符();返回0;
}