二叉链表的建立、遍历,二叉树的深度、总结点、复制、叶结点总数

#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; 
} 

  • 5
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值