(7)对二叉树进行排序,排序后的结果为二叉排序树。
二叉排序树又称二叉查找树,它或者是一棵空树,或者是具有下列性质的二叉树:(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;(3)左、右子树也分别为二叉排序树;
struct STreeNode
{
int key;
STreeNode* left_child;
STreeNode* right_child;
};
//返回值为排序后的根节点
STreeNode* bt2bst(STreeNode* root_node)
{
}
struct STreeNode
{
int key;
STreeNode* left_child;
STreeNode* right_child;
};
void InsertBST(STreeNode* t , int key)
{
if(NULL == t)
{
t = new STreeNode;
t->left_child = t->right_child = NULL;
t->key = key;
return;
}
if(key < t->key)
InsertBST(t->left_child , key);
else
InsertBST(t->right_child , key );
}
//先序遍历树并插入建立排序树
void PreOrder(STreeNode* t , STreeNode* tBST)
{
if(NULL != t)
{
InsertBST(tBST , t->key);
PreOrder(t->left_child , tBST);
PreOrder(t->right_child , tBST);
}
}
//目标函数
STreeNode* bt2bst(STreeNode* root_node)
{
STreeNode* bstTreeRoot = NULL;
PreOrder(root_node , bstTreeRoot);
return bstTreeRoot;
}
