C语言数据结构树的前序遍历算法求指教

#include <stdio.h>

typedef struct tree
{
int data;
struct tree * left;
struct tree * right;
}Tree;

void pre_order(Tree * root)//接口函数
{
if(root == NULL)
return;
else
{
printf("%d",root->data);
pre_order(root->left);//递归调用
pre_order(root->right);
}
}

int main(void)
{

return 0;
}

做到这里不会了,还请高手指教,谢谢!

第1个回答  2012-06-02
首先创建二叉树,个人喜欢用先序次序创建,如
int CreateBiTree(Tree *T)// 按先序次序输入二叉树中结点的值,'#'字符表示空树,构造二叉链表表示的二叉树T
{
char ch;
scanf("%c",&ch);
if (ch=='#') T = NULL;
else {
if (!(T = (Tree *)malloc(sizeof(Tree)))) return ERROR;
T->data=ch; // 生成根结点
CreateBiTree(T->lchild); // 构造左子树
CreateBiTree(T->rchild); // 构造右子树
}
return OK;
}
再者,调用前序遍历函数,再运用输出函数输出前序遍历的二叉树,如:
int Visit(int e ) // 输出元素e的值
{
printf("%c", e );
return OK;
}
int main()
{
Tree *T;
CreateBiTree(T); //调用按先序次序输入二叉树中结点的值(一个字符),构造二叉链
pre_order(T,Visit);//调用前序遍历二叉树算法
}
相似回答