二叉树 建立二叉树 二叉树先、中、后序遍历 计算叶结点数 、树的深度

#include<malloc.h>
#include<iostream.h>
#include<stdio.h>
int count=0, high =0,h1=0,h2=0;
struct node
{
 char data;
 node *leftChild;
 node *rigthChild;

};
typedef node *BTree;

int Init(BTree &bt)
{
 bt = (BTree) malloc (sizeof (node));
 if(bt == 0 ) return 0;
 bt =NULL;
 return 1;
}
/
//DLR create tree
// 建立二叉树
void  Create(BTree &btr)
{
 char ch;
 cin>>ch;
 if(ch=='#')
 {
  btr=NULL;
  return ;
 }
 else
 {
  btr = (BTree) malloc (sizeof (node));
  btr->data = ch;
  Create(btr->leftChild );
  Create(btr->rigthChild );
 } 
}

// output tree DLR 二叉树先序遍历
void PreOrder_DLR(BTree &root)

 if(root!=NULL)
 {
  cout<< root->data ;
  PreOrder_DLR(root->leftChild );
  PreOrder_DLR(root->rigthChild );
 }
}

// output tree LDR 二叉树中序遍历
void PreOrder_LDR(BTree &root)
{
 if(root !=NULL)
 {
  PreOrder_LDR(root->leftChild );
  cout<< root->data ;
  PreOrder_LDR(root->rigthChild );
 }
}
// output tree LRD 二叉树后序遍历
void PreOrder_LRD(BTree &root)
{
 if(root !=NULL)
 {
  PreOrder_LRD(root->leftChild );
  PreOrder_LRD(root->rigthChild );
  cout<< root->data ;
 }
}
//计算二叉树结点数
int Trav_leaf (BTree root)
{
 if(root != NULL)
 {
  if(root->leftChild == NULL && root->rigthChild == NULL ) count++;
  Trav_leaf(root->leftChild );
  Trav_leaf(root->rigthChild );
 }
 else
return count;
}

int PostTreeDepth (BTree bt)
{
 if(bt!=NULL)
 {
  h1 = PostTreeDepth (bt->leftChild ); 
  h2 = PostTreeDepth(bt->rigthChild );
  high = ( h1>=h2 )? h1:h2;
  return (high+1);
 }
 else return 0 ;

}

 

//主函数

 int main()
 {

 BTree bt;
 
 cout<<"oK !" <<endl;
 Create(bt);

 cout<<"DLR: ";
 PreOrder_DLR(bt);
 cout<<endl;
/*
 cout<<" LDR :";
 PreOrder_LDR (bt);
 cout<<endl;

 cout<<"LRD : ";
 PreOrder_LRD(bt);
 cout<<endl;
*/
 int getcout = Trav_leaf(bt);
 cout<<"叶结点数: "<<getcout<<endl;
 cout<<"树的深度:"<<PostTreeDepth(bt)<<endl;
 cout<<"high = "<<high<<"  h1 = "<<h1 <<"  h2 = "<<h2<<endl;


 return 0;
 }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值