具体实现的算法:
(1)构建二叉树
(2)前序、中序、后序遍历二叉树
(3)层次遍历二叉树
(4)求二叉树的最大宽度
(5)求二叉树的叶子结点个数
(6)交换每个结点的左右子树
(7)求二叉树的深度
代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef struct BiTNode {
char data;
struct BiTNode *lc,*rc;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T) // 构建二叉树
{
char ch;
cin >> ch;
if(ch == '#') T = NULL; //如果输入为#,代表该结点为NULL
else
{
T = new BiTNode;
T->data = ch;
CreateBiTree(T->lc);
CreateBiTree(T->rc);
}
}
void prego(BiTree T) //二叉树先序遍历(根左右)
{
if(T)
{
cout << T -> data << ' ';
xianxu(T -> lc);
xianxu(T -> rc);
}
}
void midgo(BiTree T) //二叉树中序遍历(左根右)
{
if(T)
{
zhongxu(T -> lc);
cout << T -> data << ' ';
zhongxu(T -> rc);
}
}
void reargo(BiTree T) //二叉树后序遍历(左右根)
{
if(T)
{
houxu(T -> lc);
houxu(T -> rc);
cout << T -> data << ' ';
}
}
int find(BiTree T) //查找叶子结点个数
{
if(!T) return 0;
if(T -> lc == NULL && T -> rc == NULL)
return 1;
return find(T -> lc) + find(T -> rc);
}
void change(BiTree &T) //交换每个结点的左右子树
{
if(!T) return;
swap(T-> lc,T -> rc);
change(T -> lc);
change(T -> rc);
}
void width(BiTree T ,int &maxw) //求二叉树的最大宽度
{
int tempw;
tempw = maxw = 0;
if(T == NULL) {
maxw = 0;
return ;
}
queue<BiTree>q;
BiTree last = T;
q.push(T);
while(!q.empty())
{
BiTree temp = q.front();
tempw++;
if(temp){
q.pop();
if(temp -> lc) q.push(temp -> lc);
if(temp -> rc) q.push(temp -> rc);
if(temp == last)
{
if(!q.empty())
last = q.back();
if(tempw >= maxw)
{
maxw = tempw;
tempw = 0;
}
}
}
}
}
int treedepth(BiTree T) //求二叉树的深度
{
if(!T) return 0;
return max(treedepth(T -> lc),treedepth(T -> rc)) + 1;
}
void levelgo(BiTree T) //二叉树的层次遍历
{
if(T == NULL) return;
queue<BiTree>q;
q.push(T);
while(!q.empty())
{
BiTree temp = q.front();
q.pop();
cout << temp -> data << ' ';
if(temp -> lc) q.push(temp -> lc);
if(temp -> rc) q.push(temp -> rc);
}
}
int main()
{
BiTree T = NULL;
CreateBiTree(T);
cout << find(T) << endl;
prego(T); cout << endl;
midgo(T); cout << endl;
reargo(T); cout << endl;
change(T);
xianxu(T); cout << endl;
int maxw = 0;
width(T,maxw);
cout << maxw << endl;
cout << treedepth(T) << endl;
levelgo(T); cout << endl;
return 0;
}