運行結果:ios
創建:ide
先序:spa
後續:指針
中序:blog
完整代碼:遞歸
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>
using namespace std;
#define OVERFLOW -2ci
//二叉樹的二叉鏈表存儲表示
typedef struct BiTNode{
char data;
struct BiTNode *lchild, *rchild;//左右孩子指針
}BiTNode,*BiTree;get
BiTNode* CreateTree(BiTNode *&T);//建立二叉樹
void PreOrder(BiTNode *T);//先序遍歷
void PostOrder(BiTNode *T);//後序遍歷
void InOrder(BiTNode *T);//中序遍歷string
int main()
{
BiTNode *T = NULL;
char ch1, ch2;
ch1 = 'y';
while (ch1 == 'y')
{
cout << "-----------二叉樹------------" << endl;
cout << "-------1.建立二叉樹 ------" << endl;
cout << "-------2.先序遍歷二叉樹------" << endl;
cout << "-------3.後序遍歷二叉樹------" << endl;
cout << "-------4.中序遍歷二叉樹------" << endl;
cout << "-------0.返回 ------" << endl;
cout << "-------請選擇菜單號 ------" << endl;
cin >> ch2;
getchar();
cout << endl;
switch (ch2)
{
case'1':
cout << "請輸入按先序建立二叉樹的結點序列(#表示結點爲空):";
CreateTree(T);
cout << "二叉樹建立成功"<<endl;
break;
case'2':
cout << "該二叉樹的先序遍歷爲:" << endl;
PreOrder(T);
cout << endl;
break;
case'3':
cout << "該二叉樹的後序遍歷爲:" << endl;
PostOrder(T);
cout << endl;
break;
case'4':
cout << "該二叉樹的中序遍歷爲:" << endl;
InOrder(T);
cout << endl;
break;
case'0':
ch1 = 'n';
break;
default:
cout << "輸入有誤" << endl;
}//switch
}//while
return 0;
}it
BiTNode* CreateTree(BiTNode *&T)//建立
{
char ch;
scanf("%c", &ch);
if (ch == '#')
T = NULL;
else
{
if (!(T = (BiTNode *)malloc(sizeof(BiTNode))))
exit(OVERFLOW);
T->data = ch;//生成根節點
T->lchild=CreateTree(T->lchild);//構建左子樹
T->rchild = CreateTree(T->rchild);//構建右子樹
}
return T;
}
void PreOrder(BiTNode *T)//先序遍歷
{
if (T)
{
cout << T->data;//訪問根節點
PreOrder(T->lchild);//左子樹
PreOrder(T->rchild);//右子樹
}
}
void PostOrder(BiTNode *T)//後序遍歷
{
if (T)
{
PostOrder(T->lchild);//左子樹
PostOrder(T->rchild);//右子樹
cout << T->data;//訪問根
}
}
void InOrder(BiTNode *T)//中序遍歷
{
if (T)
{
PostOrder(T->lchild);//左子樹
cout << T->data;//訪問根
PostOrder(T->rchild);//右子樹
}
}
二叉樹的建立以及遍歷都是使用遞歸的思想來進行的