二叉树的构造、遍历
//2008.04.12
#include<stdio.h>
#include<iostream>
using namespace std;
struct binaryTreeNode
{
char data;
struct binaryTreeNode *lefttree,*righttree;
};
typedef struct binaryTreeNode BinaryTree;
char ch=' ';
void CreateTree(BinaryTree *&tree)
{
if(ch!='\n')
{ ch=getchar();
if(ch=='\n')
return;
if(ch=='.')
tree=NULL;
else
{
tree=new BinaryTree;
tree->data=ch;
tree->lefttree=NULL;
tree->righttree=NULL;
CreateTree(tree->lefttree);
CreateTree(tree->righttree);
}
}
else return;
}
void PreOrder(BinaryTree *tree)
{
if(tree!=NULL)
{
putchar(tree->data);
PreOrder(tree->lefttree);
PreOrder(tree->righttree);
}
}
void InOrder(BinaryTree *tree)
{
if(tree!=NULL)
{
InOrder(tree->lefttree);
putchar(tree->data);
InOrder(tree->righttree);
}
}
void PostOrder(BinaryTree *tree)
{
if(tree!=NULL)
{
PostOrder(tree->lefttree);
PostOrder(tree->righttree);
putchar(tree->data);
}
}
int main()
{
BinaryTree *t=NULL;
cout<<"(输入时以前序和完全二叉树的形式,空结点用'.'代替,遇到叶子结点时加输两个'.')"<<endl;
cout<<"请输入一串字符串:"<<endl;
CreateTree(t);
cout<<"按前序遍历:"<<endl;
PreOrder(t);
cout<<endl;
cout<<"按中序遍历:"<<endl;
InOrder(t);
cout<<endl;
cout<<"按后序遍历:"<<endl;
PostOrder(t);
cout<<endl;
return 0;
}