//二叉樹的遍歷
//按先序序列建立一棵二叉樹,按照ABC@@D@@E@F@@輸入字符,@代表層數並查找D所在層數
//定義二叉樹
typedef struct BiTNode
{
char data;
struct BiTNode *lchild, *rchild;
}BiTNode,*BiTree;
//按先序創建一棵二叉樹
void creatBiTree(BiTree *T)
{
char c;
cin >> c;
if (c == ' ') *T = NULL;
else
{
*T = new BiTNode;
(*T)->data = c;
creatBiTree(&(*T)->lchild);
creatBiTree(&(*T)->rchild);
}
}
void visit(char c, int level)
{
if (c == 'D') cout << c << "在" << level <<"層"<< endl;
}
//先序遍歷這棵二叉樹
void preOrderTraverse(BiTree T,int level)
{
if (T)
{
visit(T->data, level);
preOrderTraverse(T->lchild, level+1);
preOrderTraverse(T->rchild,level+1);
}
}
int main()
{
int level = 1;
BiTree T = NULL;
creatBiTree(&T);
preOrderTraverse(T, level);
system("pause");
return 0;
}
你運行有什麼問題 嗎