二叉树是数据结构的一个重点,这些天学了一下,写了一下代码,虽然有点局限性(每节点只能表示不同的字符),但也与大家分享一下
主要内容:
二叉树的建立(通过先序和中序确定),判断是否为满二叉树或完全二叉树,求深度和叶子书
//二叉树的建立
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;
};