此处承接篇一
4. 根据两种序列来创建二叉树
(1)已知前序和中序,来创建二叉树
int FindIs(char *is,int n,ElemType x)
{
for(int i = 0;i<n;++i)
{
if(is[i] == x)
return i;
}
return -1;
}
BtNode* Create(char *ps,char *is,int n)
{
BtNode* s = NULL;
if(n > 0)
{
s = Buynode();
s->data = ps[0];
int pos = FindIs(is,n,ps[0]);
if(pos == -1) exit(1);
s->leftchild = Create(ps+1,is,pos);
s->rightchild = Create(ps+pos+1,is+pos+1,n-pos-1);
}
return s;
}
BtNode* CreatePI(char *ps,char *is)
{
if(ps == NULL || is == NULL)
{
return NULL;
}else
{
int n = strlen(ps);
return Create(ps,is,n);
}
}
(2) 已知中序和后序,来创建二叉树
BtNode* CreateNi(char *is, char *ls, int n)
{
BtNode* s = NULL;
if (n > 0)
{
s = buyNode();
s->data = ls[n-1];
int pos = findIs(is, n, ls[n-1]);
if (pos == -1)
{
exit(1);
}
s->child_left = CreateNi(is, ls, pos);
s->child_right = CreateNi(is + pos + 1, ls + pos, n - pos - 1);
}
return s;
}
BtNode* CreateIL(char *is, char *ls)
{
if (is == NULL || ls == NULL)
{
return NULL;
}
return CreateNi(is, ls, strlen(is));
}
值得注意的是,根据前序和后序根本无法创建出二叉树,因为根据前序的特征,第一个数据为根,根据后序,最后一个数据为根,且两者为同一数据,故无法根据根来划分出左子树和右子树,所以无法创建出二叉树。
5.其他函数
(1)二叉树的深度
int Depth(BtNode *ptr)
{
if(ptr == NULL)
{
return 0;
}else
{
return Max(Depth(ptr->leftchild),Depth(ptr->rightchild)) + 1;
}
}
(2)二叉树的叶子节点个数
int SizeLeaf(BtNode *ptr)
{
if(ptr == NULL)
return 0;
else if(ptr->leftchild == NULL && ptr->rightchild == NULL)
{
return 1;
}else
{
return SizeLeaf(ptr->leftchild)+SizeLeaf(ptr->rightchild);
}
}
(3)二叉树的结点个数
int Size(BtNode *ptr)
{
if(ptr == NULL)
return 0;
else
return 1+Size(ptr->leftchild)+Size(ptr->rightchild);
}
(4)查找某个元素
BtNode * FindValue(BtNode *ptr,ElemType x)
{
if(ptr == NULL || ptr->data == x)
{
return ptr;
}else
{
BtNode *p = FindValue(ptr->leftchild,x);
if(NULL == p)
{
p = FindValue(ptr->rightchild,x);
}
return p;
}
}
(5)某子树的父结点
BtNode * Parent(BtNode *ptr,BtNode *child)
{
if (ptr ==NULL ||ptr->leftchild ==child ||ptr->rightchild ==child)
{
return ptr;
}
else
{
BtNode *p = Parent(ptr->leftchild,child);
if (NULL == p)
{
p = Parent(ptr->rightchild,child);
}
return p;
}
}
BtNode * FindParent(BtNode *ptr,BtNode *child)
{
if (ptr ==NULL ||child ==NULL ||ptr ==child)
{
return NULL;
}
else
{
return Parent(ptr,child);
}
}
(6)判断两个二叉树是否相等
bool Equal(BtNode *pa,BtNode *pb)
{
return (pa ==NULL &&pb ==NULL) ||
(pa !=NULL &&pb !=NULL &&pa->data ==pb->data &&
Equal(pa->leftchild,pb->leftchild) &&
Equal(pa->rightchild,pb->rightchild));
}
6.后期补充
bool Is_Full_BinaryTree(BtNode *ptr);
bool Is_Comp_BinaryTree(BtNode *ptr);
bool Is_Balance_BinaryTree(BtNode *ptr);
int RetTwoPMaxPath(BtNode *ptr, BtNode *&child1, BtNode *&child2);
int SizeBinaryBrch(BtNode *ptr);
int SizeOneBrch(BtNode *ptr);
int SizeOneLBrch(BtNode *ptr);
int SizeOneRBrch(BtNode *ptr);
int MaxPath(BtNode *ptr);
RetNode RetTwoPMaxPath(BtNode *ptr);