//........二叉树遍历算法应用 ...........
#include<iostream>
using namespace std;
typedef char dataType;
typedef struct node
{
dataType data;
node *lchild, *rchild;
}* BTREE;
// show
void show(BTREE bt)
{
if (bt)
{
show(bt->lchild);
cout << bt->data << ends;
show(bt->rchild);
}
}
//输入二叉树的先序序列,构造这棵二叉树
BTREE creatBT()
{
dataType ch;
ch = getchar();
if (ch == '#') return NULL;
else
{
BTREE p = (BTREE)malloc(sizeof(node));
p->data = ch;
p->lchild = creatBT();
p->rchild = creatBT();
return p;
}
}
//计算二叉树的叶子节点数目
void leafNum(BTREE bt, int &count)
{
if (bt)
{
if (bt->lchild == NULL && bt->rchild == NULL) count++;
leafNum(bt->lchild, count);
leafNum(bt->rchild, count);
}
}
//计算二叉树的高度
int BThigh(BTREE bt)
{
if (bt == NULL) return 0;
else
{
int h1 = BThigh(bt->lchild);
int h2 = BThigh(bt->rchild);
return 1 + (h1 > h2 ? h1 : h2);
}
}
//交换二叉树的左右子树
void exchange(BTREE bt)
{
if (bt)
{
exchange(bt->lchild);
exchange(bt->rchild);
BTREE temp = bt->rchild ;
bt->rchild = bt->lchild;
bt->lchild = temp;
}
}
int main()
{
BTREE bt;
bt = creatBT();
show(bt);
cout << endl;
int s = 0;
leafNum(bt, s);
cout << "叶子节点数目s = " << s << endl;
int high = BThigh(bt);
cout << "the highth of tree is :" << high << endl;
exchange(bt);
show(bt);
cout << endl;
system("pause");
return 0;
}
二叉树遍历算法的应用
最新推荐文章于 2023-04-02 19:41:00 发布