题目:把二叉查找树转换成排序的双向链表
输入:一个二叉查找树
输出:排序的双向链表;
要求:不能创建任何新的节点,只能调整指针的方向;
实现
思路:对二叉查找树进行中序遍历,对遍历的当前节点加入到链表末尾即可;加入链表的head和tail,当前的节点curr:
curr->next=null;curr->pre=tail;tail->next=curr;tail=curr;
实现代码:
public class Num1 {
public static BSTreeNode head=null;
public static BSTreeNode tail=null;
/*
* insert search tree to double link
*/
public static void main(String[] args) {
//create a search tree to test
BSTreeNode root=null;
root=addBSTreeNode(root,10);
addBSTreeNode(root,6);
addBSTreeNode(root,14);
addBSTreeNode(root,4);
addBSTreeNode(root,8);
addBSTreeNode(root,12);
addBSTreeNode(root,16);
inOrderBSTree(root);
//print result
BSTreeNode node=head;
while(node.right!=null){
System.out.print(node.value+" ");
node=node.right;
}
}
public static BSTreeNode addBSTreeNode(BSTreeNode root,int value){
BSTreeNode node=new BSTreeNode(value,null,null);
if(root==null){
root=node;
return root;
}
BSTreeNode curr=root;
BSTreeNode parent=null;
while(curr!=null){
parent=curr;
if(curr.value<value){
curr=curr.right;
}else{
curr=curr.left;
}
}
//insert node to parent's child
if(parent.value<value){
parent.right=node;
}else{
parent.left=node;
}
return root;
}
public static void inOrderBSTree(BSTreeNode root){
if(root==null){
return;
}
if(root.left!=null){
inOrderBSTree(root.left);
}
//System.out.println(root.value);
convertIntoDoubleList(root);
if(root.right!=null){
inOrderBSTree(root.right);
}
}
private static void convertIntoDoubleList(BSTreeNode node) {
node.left=tail;
if(tail==null){
head=node;
}else{
tail.right=node;
}
tail=node;
}
}
class BSTreeNode{
int value;
BSTreeNode left;
BSTreeNode right;
public BSTreeNode(int value,BSTreeNode left,BSTreeNode right){
this.value=value;
this.left=left;
this.right=right;
}
public BSTreeNode(int value){
this(value,null,null);
}
}