二叉树的操作

二叉树是数据结构的一个重点,这些天学了一下,写了一下代码,虽然有点局限性(每节点只能表示不同的字符),但也与大家分享一下

主要内容:
二叉树的建立(通过先序和中序确定),判断是否为满二叉树或完全二叉树,求深度和叶子书

//二叉树的建立
struct Item* CTree::Creat(CString pri, CString mid)
{
 if(pri.GetLength())
 {
  struct Item *p = new struct Item;
  root = p;
  p->data = pri.GetAt(0);
  for(int i = 0;i<mid.GetLength()&&(mid.GetAt(i) != pri.GetAt(0));i++);
  CString pt,mt;
  if(i<mid.GetLength()&&i != 0)
  {
   int k;
   for(k = 0;k<i;k++)
    mt += mid.GetAt(k);
   for(k = 1;k<i+1;k++)
    pt += pri.GetAt(k);
  }
  CTree t;
  p->lchild = t.Creat(pt,mt);            //递归建立左子树
  pt.Empty();
  mt.Empty();

  if(i<mid.GetLength())
  {
   int k;
   for(k = i+1;k<mid.GetLength();k++)
    mt += mid.GetAt(k);
   for(k = i+1;k<pri.GetLength();k++)
    pt += pri.GetAt(k);
  }
  CTree t1;
  p->rchild = t1.Creat(pt,mt);                //递归建立右子树
  return p;
 }
 return NULL;
}

//求深度
int CTree::Depth(struct Item* temp)
{
        int lh = 1;
        int rh = 1;

        if(!temp)
                return 0;
        if(temp->lchild)
                lh += Depth(temp->lchild);
        if(temp->rchild)
                rh += Depth(temp->rchild);
        return lh>rh?lh:rh;
}

//判断是否为完全二叉树
BOOL CTree::IsEntire(struct Item* temp)
{
 if(IsFull(temp))
  return TRUE;
 else
 {
  if(!temp)
   return TRUE;
  if(IsFull(temp->lchild))
  {
   if(IsEntire(temp->rchild))
    if(Depth(temp->lchild) == Depth(temp->rchild))
     return TRUE;
   if(IsFull(temp->rchild))
    if(Depth(temp->lchild)-1 == Depth(temp->rchild)||Depth(temp->lchild) == Depth(temp->rchild))
     return TRUE;
  }
  else
  {
   if(IsEntire(temp->lchild))
    if(IsFull(temp->rchild))
     if(Depth(temp->lchild)-1 == Depth(temp->rchild))
      return TRUE;
  }
 }
 return FALSE; 
}

//判断是否为满二叉树
BOOL CTree::IsFull(struct Item* temp)
{
 BOOL right = FALSE;
 BOOL left = FALSE;
 if(!temp)
  return TRUE;
 if(temp->lchild == NULL&&temp->rchild == NULL)
 {
  return TRUE;
 }
 else
 {
  if(temp->lchild&&temp->rchild&&Depth(temp->lchild)==Depth(temp->rchild))
  {
   left = IsFull(temp->lchild);
   right = IsFull(temp->rchild);
  }
  if(left&&right)
   return TRUE;
 }
 return FALSE;
}

//求叶子数
int CTree::GetLeafNum(struct Item* temp)
{
 int n = 0;
 
 if(temp->lchild == NULL && temp->rchild == NULL)
 {
  n++;
 }
 else
 {
  if(temp->lchild)
   n += GetLeafNum(temp->lchild);
  if(temp->rchild)
   n += GetLeafNum(temp->rchild);
 }
 return n;
}

 

以上所用的结构Item为:
struct Item
{
 char data;
 struct Item *rchild,*lchild;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值