1.树结点定义
typedef struct BTNode
{
char data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
2.先序遍历
void visit(BTNode *p)
{
/*TO DO VISIT*/
cout<<p->data;
return;
}
void preorder(BTNode *p)
{
if(p)
{
visit(p);
preorder(p->lchild);
preorder(p->rchild);
}
}
3.创建二叉树
void createBinaryTree(BTNode *&p)
{
char ch;
cin>>ch;
if(ch=='#')
p=NULL;
else
{
p=(BTNode*)malloc(sizeof(BTNode));
p->data=ch;
createBinaryTree(p->lchild);
createBinaryTree(p->rchild);
}
}
4.主函数
void main()
{
BTNode *p;
p=NULL;
createBinaryTree(p);
preorder(p);
}
输入:AB#D##C##
运行结果:ABDC