#include <cstdlib>
#include <iostream>
#define OVERFLOW 1
#define OK 1
#define ERROR -1
typedef int Status;
typedef char TElemType;
typedef struct BiTNode{
TElemType data;
BiTNode *lchild;
BiTNode *rchild;
}BiTNode, *BiTree;
Status CreateBiTreeByPreOrder (BiTree &T){
//这里的函数形参不能是*T,如果是*T的话,建立起来的是以T的拷贝为根的树,而不是T.
//相当于值传递,这里应该用二级指针. 具体可参考:
http://bbs.csdn.net/topics/390086990
TElemType ch;
std::cin >> ch;
if (ch == '#'){
// if (ch == ‘ ’)
//这有个问题一直弄不明白,为什么用‘ ’的时候,无法结束呢???翻了翻C++ primer发现cin>>读取时,
//忽略开头所有的空白字符,如空格,换行符,tab等,直到再遇到空白字符时,读取终止。
T = NULL;
}else {
T = (BiTree) malloc (sizeof (BiTNode));
if (!T) exit(OVERFLOW);
T->data = ch;
CreateBiTreeByPreOrder (T->lchild);
CreateBiTreeByPreOrder (T->rchild);
}
return OK;
}//CreateBiTree
//Visit functor.
Status PrintElement (TElemType e){
std::cout<< e <<std::endl;
return OK;
}
//PreOrderTraverse
int PreOrderTraverse (BiTree &T, Status (*Visit)(TElemType e)){
if (T){
if (Visit (T->data))
if (PreOrderTraverse (T->lchild, Visit))
if (PreOrderTraverse (T->rchild, Visit)) return OK;
return ERROR;
}else return OK;
}
int main(int argc, char *argv[])
{
BiTree tree;
CreateBiTreeByPreOrder (tree);
PreOrderTraverse (tree, PrintElement);
system("PAUSE");
return EXIT_SUCCESS;
}