#include
#include
using namespace std;
int LeafNum;// 葉子結點數
//二叉鏈表的結構類型定義
const int maxsize = 20;
typedef char datatype;
typedef struct Binode
{
datatype data;
struct Binode *lchild, *rchild;
}BiTree;
BiTree*creattree()
{
char ch;
BiTree*Q[maxsize];
int front, rear;
BiTree *root, *s;
root = NULL;
front = 1;
rear = 0;
cout << "按層次輸入二叉樹,以'#'結束輸入:"<
cin >> ch;
while (ch!= '#')
{
rear++;
s = new BiTree;
s->data = ch;
s->lchild = s->rchild=NULL;
Q[rear] = s;
if (rear == 1)
root = s;
else
{
if (rear % 2 == 0)Q[front]->lchild = s;
else {
Q[front]->rchild = s;
front++;
}
}
cin >> ch;
}
return root;
}
//遞歸方法先序遍歷二叉樹
void preOrder(BiTree *T)
{
if(T) //若非空
{
if(T->data)
{ //輸出
printf("%c",T->data);
}
preOrder(T->lchild);
preOrder(T->rchild);
}
}
//遞歸方法中序遍歷二叉樹
void inOrder(BiTree *T)
{
if(T) //若非空
{
preOrder(T->lchild);
if(T->data)
{ //輸出
printf("%c",T->data);
}
preOrder(T->rchild);
}
}
//遞歸方法後序遍歷二叉樹
void postOrder(BiTree* T)
{
if(T) //若非空
{
preOrder(T->lchild);
preOrder(T->rchild);
if(T->data)
{ //輸出
printf("%c",T->data);
}
}
}
//後序遍歷求二叉樹的高度遞歸算法
int PostTreeDepth(BiTree *T)
{
int hl,hr,max;
if(T!=NULL)
{
hl=PostTreeDepth(T->lchild); //求左子樹的深度
hr=PostTreeDepth(T->rchild); //求右子樹的深度
max=hl>hr?hl:hr; //得到左、右子樹深度較大者
return(max+1); //返回樹的深度
}
else
return(0); //如果是空樹,則返回0
}
//葉子結點的個數以及元素
int TreeLeaf(BiTree *T)
{
if(T)
{
if(!T->lchild&&!T->rchild)
{
LeafNum++;
cout<<T->data<<" ";
}
TreeLeaf(T->lchild);
TreeLeaf(T->rchild);
}
return LeafNum;
}
int main()
{
BiTree *T;
cout<<"創建二叉樹"<<endl;
BiTree*creattree();
cout<<"先序遍歷:";
preOrder(T);
cout<<endl;
cout<<"中序遍歷:";
inOrder(T);
cout<<endl;
cout<<"後序遍歷:";
postOrder(T);
cout<<endl;
cout<<"葉子結點為:";
cout<<"葉子結點個數為:"<<TreeLeaf(T)<<endl;
cout<<"樹的的深度:";
cout<<PostTreeDepth(T)<<endl;
return 0;
}
BiTree*creattree();
->
T = creattree();