二叉排序树与平衡二叉树的实现
问题描述
分别采用二叉链表和顺序表作存储结构,实现对二叉排序树与平衡二叉树的操作。
基本要求
用二叉链表作存储结构实现二叉排序树
1)以回车符(‘\n’)为输入结束标志,输入数列L,生成一棵二叉排序树T;
2)对二叉排序树T作中序遍历,输出结果;
3)计算二叉排序树T查找成功的平均查找长度,输出结果;
4)输入元素x,查找二叉排序树T,若存在含x的结点,则删除该结点,并作中序遍历(执行操作2);否则,输出信息“无x”;
用顺序表(一维数组)作存储结构----静态链表
1)以回车符(‘\n’)为输入结束标志,输入数列L,生成一棵二叉排序树T;
2)对二叉排序树T作中序遍历,输出结果;
3)计算二叉排序树T查找成功的平均查找长度,输出结果;
4)输入元素x,查找二叉排序树T,若存在含x的结点,则删除该结点,并作中序遍历(执行操作2);否则,输出信息“无x”;
用二叉链表作存储结构实平衡的二叉排序树
1)用数列L,生成平衡的二叉排序树BT:当插入新元素之后,发现当前的二叉排序树BT不是平衡的二叉排序树,则立即将它转换成新的平衡的二叉排序树BT;
2)计算平衡的二叉排序树BT的平均查找长度,输出结果
算法思路
首先把输入的值输入到array数组里
void BinaryTree::toArray(QString content)
{
QStringList listOfNum=content.split(" ");
for(int i=0;i<listOfNum.size();i++)
{
array[i]=listOfNum[i].toInt();
root=insertToLinkedList(root,array[i]);
insertToContiguousList(0,array[i]);
qDebug()<<array[i];
numberOfNode=i+1;
qDebug()<<"结点数"<<numberOfNode;
}
}
二叉链表的中序遍历
void BinaryTree::InOrder_LinkedList(TreeNode* node)
{
if (node==NULL)
{
qDebug()<<"结点为空";
}
else
{
InOrder_LinkedList(node->LeftChild);
ui->textShow->insertPlainText(QString::number(node->value));
ui->textShow->insertPlainText(" ");
qDebug()<<node->value;
InOrder_LinkedList(node->RightChild);
}
}
二叉链表求平均查找长度ASL
void BinaryTree::AverageSearchLength_LinkedList(TreeNode* root2)
{
for(int i=0;i<numberOfNode;i++)
{
Search_LinkedList(root2,array[i]);
}
ASL=ASL/numberOfNode;
ui->textShow->append("平均查找长度");
ui->textShow->insertPlainText(QString::number(ASL));
ui->textShow->append("");
}
查找并删除元素
void BinaryTree::SearchAndDelete_LinkedList(QString x)
{
int k=x.toInt();
TreeNode* p=Search_LinkedList(root,k);
if(p==NULL)
{
ui->textShow->append("无");
ui->textShow->insertPlainText(QString::number(k));
}
else
{
TreeNode* ptr=p;
TreeNode* parent=Parent_LinkedList(p);
if(p->LeftChild!=NULL&&p->RightChild!=NULL)
{
parent=p;
p=p->RightChild;
while(p->LeftChild!=NULL)
{
parent=p;
p=p->LeftChild;
}
}
TreeNode* child=(p->LeftChild!=NULL)?p->LeftChild:p->RightChild;
if(parent==NULL)
{
root=child;
}
else
{
if(parent->LeftChild==p)
{
parent->LeftChild=child;
}
else{
parent->RightChild=child;
}
}
if(ptr!=p)
{
ptr->value=p->value;
}
ui->textShow->append("用链表查找并删除结点的结果:");
InOrder_LinkedList(root);
}
}