二叉查找树的Find,FindMin,FindMax的递归和非递归实现

typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree; struct TreeNode{
ElementType X;
SearchTree Left;
SearchTree Right;
}; //建立一颗空树的例程
SearchTree
MakeEmpty( SearchTree T )
{
if( T != NULL )
{//先做空儿子,在弄父亲
MakeEmpty(T->Left);
MakeEmpty(T->Right);
free(T);
}
return NULL;//避免返回值的警告
}
//二叉查找树的Find操作(尾递归)
SearchTree
Find( SearchTree T, ElementType X )
{
if( T == NULL )
return NULL;
if( T->Element > X )
return Find( T->Left, X );
else if( T->Element < X )
return Find( T->Right, X );
else
return T;
}
//对二叉查找树FindMin操作(非递归实现,自创)
SearchTree
FindMin( SearchTree T )
{
SearchTree Tmp; if(T == NULL )
return NULL;//空树 Tmp = T->Left;
while( Tmp != NULL )
{
T = Tmp;
Tmp = Tmp->Left;
}
return T->Element;
}
//FindMin操作非递归实现正解
SearchTree
FindMin( SearchTree T )
{
if(T != NULL )
{
while( T->Left != NULL )
T = T->Left;
}
return T;
}
//FindMin递归正解
SearchTree
FindMin( SearchTree T )
{
if( T == NULL )
return NULL;
if( T->Left != NULL ){
T = T->Left;
return FindMin( T );
}
else
return T;
}
//FindMax非递归
SearchTree
FindMax( SearchTree T )
{
if( T == NULL )
return NULL;
while( T->Right != NULL )
{
T = T->Right;
}
return T;
}
//FindMax递归
SearchTree
FindMax( SearchTree T )
{
if( T == NULL )
return NULL;
if( T->Right != NULL ){
T = T->Right;
return FindMax( T );
}
return T;
}
//FindMax递归超正解
SearchTree
FindMax( SearchTree T )
{
if( T == NULL )
return NULL;
else
if( T->Right == NULL )
return T;
else
return FindMax( T->Right );
}

二叉树的节点儿子不多于两个,针对每个节点,且左子树所有数比节点小,右子树所有数比节点大

上一篇:pinyin utils


下一篇:win10+VS2015+opencv3.4.0配置方法