思路一:到达某一节点,先调整其左子树为有序链表,再调整右子树为双向链表,再调整当前节点与左右子树的链接。
//主函数
public void changeToList()
{
//root为树的根节点,没有验证空树
root.left=findlast(change(root.left));
root.right=findfirst(change(root.right));
root.left.right=root;
root.right.left=root;
}
//转换函数
private AvlTreeNode<Anytype> change(AvlTreeNode<Anytype> t)
{
if(t==null)
return t;
if(t.left == null && t.right == null)
{
return t;
}
else if(t.left==null && t.right !=null)
{
t.right=changeright(t.right);
t.right.left=t;
}
else if(t.right==null && t.left != null)
{
t.left=changeleft(t.left);
t.left.right=t;
}
else
{
t.left=changeleft(t.left);
t.left.right=t;
t.right=changeright(t.right);
t.right.left=t;
}
return t;
}
//找到排序完链表的头节点
private AvlTreeNode<Anytype> findfirst(AvlTreeNode<Anytype> t)
{
while(true)
{
if(t.left != null)
{
t=t.left;
}
else
{
break;
}
}
return t;
}
//找到排序完链表的尾节点
private AvlTreeNode<Anytype> findlast(AvlTreeNode<Anytype> t)
{
while(true)
{
if(t.right != null)
{
t=t.right;
}
else
{
break;
}
}
return t;
}