判断是否是二叉排序树:
下面采用采用两种方法,1.递归的进行判断。2.用中序遍历判断。
后更:第一种方法实际上是错误的,按照[5,3,0,0,1,6]这棵树用这个方法判断出来是二叉排序树,但是实际上却是错误的。
bool JudgeTree1(BiTree Tree)
{
if (Tree==NULL)
{
return true;
}
if (Tree->lchild==NULL)
{
return true;
}
else if ((Tree->data)<(Tree->lchild->data))
{
return false;
}
if (Tree->rchild==NULL)
{
return true;
}
else if((Tree->data)>(Tree->rchild->data))
{
return false;
}
if (JudgeTree1(Tree->lchild)==false)
{
return false;
}
if (JudgeTree1(Tree->rchild)==false)
{
return false;
}
return true;
}
//中序遍历
static ElemType Num = INT_MIN;
bool JudgeTree2(BiTree Tree,ElemType *pNum = &Num)
{
if (Tree==NULL)
{
return true;
}
JudgeTree2(Tree->lchild,pNum);
if (Tree->data>(*pNum))
{
(*pNum) = Tree->data;
}
else
{
return false;
}
JudgeTree2(Tree->rchild,pNum);
}
判断是否是平衡二叉树:
判断大小,一个个节点判断,同上方法1;
判断平衡因子,自底向上一边积累树的高度一边计算差值。
int JudgeAVL(BiTree Tree,bool *Result)
{
if (Tree==NULL||(*Result)==false)
{
return 0;
}
//判断大小关系对不对
if (Tree->lchild!=NULL)
{
if ((Tree->data)<(Tree->lchild->data))
{
(*Result)=false;
return 0;
}
}
if (Tree->rchild!=NULL)
{
if((Tree->data)>(Tree->rchild->data))
{
(*Result)=false;
return 0;
}
}
int L_High,R_High;
L_High = JudgeAVL(Tree->lchild,Result);
R_High = JudgeAVL(Tree->rchild,Result);
if (abs(L_High-R_High)>=2)
{
(*Result) = false;
}
return getMax(L_High,R_High)+1;
}