回 帖 发 新 帖 刷新版面

主题:[讨论]请教二叉树的基本操作的C语言实现(请各位高手指点)

这是我的程序,"PreorderTraverse(BiTreeNode *t,Visit(char item))"总是提示定义错误,请各位高手指正
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#define null 0
typedef struct node
{
char data;
struct node *leftchild;
struct node *rightchild;
}BiTreeNode;

void Initiate(BiTreeNode **root)
{
*root=(BiTreeNode*)malloc(sizeof(char));
(*root)->leftchild=null;
(*root)->rightchild=null;
}

BiTreeNode *InsertleftNode(BiTreeNode *cur,char x)
{
BiTreeNode *s,*t;
if(cur==null)return null;
t=cur->leftchild;
s=(BiTreeNode*)malloc(sizeof(char));
s->data=x;
s->leftchild=t;
s->rightchild=null;
cur->leftchild=s;
return cur->leftchild;
}

BiTreeNode *InsertrightNode(BiTreeNode *cur,char x)
{
BiTreeNode *s,*t;
if(cur==null)return null;
t=cur->rightchild;
s=(BiTreeNode*)malloc(sizeof(char));
s->data=x;
s->rightchild=t;
s->leftchild=null;
cur->rightchild=s;
return cur->rightchild;
}
destroy(BiTreeNode **root)
{
if((*root)!=null&&(*root)->leftchild!=null)
destroy(&(*root)->leftchild);
if((*root)!=null&&(*root)->rightchild!=null)
destroy(&(*root)->rightchild);
free(*root);
}

BiTreeNode *DeleteLeftTree(BiTreeNode *cur)
{
if(cur==null||cur->leftchild==null)return null;
destroy(&cur->leftchild);
cur->leftchild=null;
return cur;
}

BiTreeNode *DeleterightTree(BiTreeNode *cur)
{
if(cur==null||cur->rightchild==null)return null;
destroy(&cur->rightchild);
cur->rightchild=null;
return cur;
}

PreorderTraverse(BiTreeNode *t,Visit(char item))
{
if(t!=null)
{
Visit(t->data);
PreOrderTraverse(t->leftChild,Visit);
PreOrderTraverse(t->rightChild,Visit);
}
}

InorderTraverse(BiTreeNode *t,Visit(char item))
{
if(t!=null)
{
InOrderTraverse(t->leftChild,Visit);
Visit(t->data);
InOrderTraverse(t->rightChild,Visit);
}
}

PostorderTraverse(BiTreeNode *t,Visit(char item))
{
if(t!=null)
{
PostOrderTraverse(t->leftChild,Visit);
PostOrderTraverse(t->rightChild,Visit);
Visit(t->data);
}
}

Visit(char item)
{
printf("%c",item);
}



PrintBiTree(BiTreeNode *t,int n)
{
int i;
if(t==Null)return;
PrintBiTree(t->rightChild,n+1);
for(i=0;i<n-1;i++)printf("");
if(n>0)
{
printf("---");
printf("%c\n",t->data);
}
PrintBiTree(t->leftChild,n+1);
}

main()
{
BiTreeNode *root, *p,*q;
Initiate(&root);
p=InsertLeftNode(root,'A');
p=InsertLeftNode(p,'B');
p=InsertLeftNode(p,'D');
p=InsertRightNode(p,'G');
p=InsertRightNode(root->leftchild,'C');
q=p;
InsertLeftNode(p,'E');
InsertRightNode(q,'F');
PrintBiTree(t,0);
printf("前序遍历:");
PreOrderTraverse(root->leftChild,Visit);
printf("\n中序遍历:");
InOrderTraverse(root->leftChild,Visit);
printf("\n后序遍历:");
PostOrderTraverse(root->leftChild,Visit);
Destroy(&root);
}

回复列表 (共2个回复)

沙发

哦,你是想弄个函数接口是吧。。。这有必要吗?

一般都要用到函数的返回类型,不能像这样省掉的,空类型用void

void PreorderTraverse(BiTreeNode *t,void (*Visit)(char))
{
if(t!=null)
{
Visit(t->data);
PreOrderTraverse(t->leftChild,Visit);
PreOrderTraverse(t->rightChild,Visit);
}
}
void Visit(char item)
{
...
}

板凳

复习函数指针

我来回复

您尚未登录,请登录后再回复。点此登录或注册