把二元查找树转变成排序的双向链表(JAVA)

来源:互联网 发布:淘宝商品被下架售后 编辑:程序博客网 时间:2024/06/04 14:23

思路一:到达某一节点,先调整其左子树为有序链表,再调整右子树为双向链表,再调整当前节点与左右子树的链接。

//主函数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;}