#include<iostream>
using namespace std;
//二叉树的二叉链表存储表示
typedef struct BiNode
{
char data; //结点数据域
struct BiNode *lchild,*rchild; //左右孩子指针
}BiTNode,*BiTree;
//建立二叉链表
void CreateBiTree(BiTree &T)
{
//按先序次序输入二叉树中结点的值(一个字符),创建二叉链表表示的二叉树T
char ch;
cin >> ch;
if(ch=='#') T=NULL; //递归结束,建空树
else{
T=new BiTNode;
T->data=ch; //生成根结点
CreateBiTree(T->lchild); //递归创建左子树
CreateBiTree(T->rchild); //递归创建右子树
} //else
}
//中序遍历的递归算法
void InorderTraverse(BiTree T)
{
if(T)
{
InorderTraverse(T->lchild);
cout<<T->data;
InorderTraverse(T->rchild);
}
}
//后序遍历的递归算法
void PostorderTraverse(BiTree T)
{
if(T)
{
PostorderTraverse(T->lchild);
PostorderTraverse(T->rchild);
cout<<T->data;
}
}
//复制二叉树
void Copy(BiTree T,BiTree &NewT)
{
if(T==NULL)//如果是空树,递归结束
{
NewT=NULL;
return;
}
else{
NewT=new BiTNode;
NewT->data=T->data;//复制根结点
Copy(T->lchild,NewT->lchild);//递归复制左子树
Copy(T->rchild,NewT->rchild);//递归复制右子树
}
}
// 计算二叉树的深度
int Depth(BiTree T)
{ int m,n;
if(T==NULL) return 0; //如果是空树,深度为0;递归结束
else{
m=Depth(T->lchild); //递归计算左子树的深度记为m
n=Depth(T->rchild);
if(m>n) return m+1; //二叉树的深度为吗,m,n的最大者
else
return n+1;
}
}
//统计二叉树中的结点个数
int NodeCount(BiTree T)
{ //int m,n;
if(T==NULL) return 0;
/*else{
m=NodeCount(T->lchild);
n=NodeCount(T->rchild);
return m+n+1;
} */
else
return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
}
//统计二叉树中叶结点的个数
void Countleaf(BiTree T,int &count)
{
if(T)
{
if(!(T->lchild)&&!(T->rchild))
count++; //对叶子结点计数
Countleaf(T->lchild,count );
Countleaf(T->rchild,count );
}
}
int main()
{
BiTNode *tree,*tree1;
int count1=0;
cout<<"输入先序建立二叉链表的序列:\n";
CreateBiTree(tree);
cout<<"中序遍历二叉链表结果为:\n";
InorderTraverse(tree);
cout<<endl;
cout<<"后序遍历二叉链表结果为:\n";
PostorderTraverse(tree);
cout<<endl;
Copy(tree,tree1);
cout<<"复制得到的新树的中序序列:\n";
InorderTraverse(tree1);
cout<<endl;
cout<<"该二叉树的深度为:"<<Depth(tree)<<endl;
cout<<"该二叉树的总结点为:"<<NodeCount(tree)<<"个\n";
Countleaf(tree,count1 );
cout<<"该二叉树的叶结点总数为:"<<count1<<endl;
return 0;
}
二叉链表的建立、遍历,二叉树的深度、总结点、复制、叶结点总数
最新推荐文章于 2020-11-24 12:50:44 发布