package questions;
/**
* @title 把二元查找树转变成排序的双向链表
* @question 输入一颗二元查找树,将该二元查找树转换成一个排序的双向链表。要求不能创建任何新结点,只能调整指针的指向。<br>
* .... 10<br>
* .... /\<br>
* ... 6 14<br>
* .. /\ /\<br>
* . 4 8 12 16<br>
* 转换成双向链表 4=6=8=10=12=14=16
* @author Sam
*
*/
public class Ex1o2o1 {
static BSTreeNode pHeader = null;// 指向循环队列头结点
static BSTreeNode pPrevios = null;// 指向前一个结点
/**
* 1.构造二叉树查找树;<br>
* 2.中序遍历二叉树查找,因此结点按从小到大顺序访问,假设之前访问过的结点已经调整为一个双向链表,那么<br>
* 3.只需要将当前结点连接至双向链表的最后一个结点即可,访问完毕后,双向链表也就调整好了。
*
* @param args
*/
public static void main(String[] args) {
BSTreeNode tree = new BSTreeNode();
tree.add(10);
tree.add(6);
tree.add(14);
tree.add(4);
tree.add(8);
tree.add(12);
tree.add(16);
inOrderBSTree(tree);
// 验证
System.out.print("验证正向链接:");
BSTreeNode node = pHeader;
while (null != node) {
System.out.print(String.format(" %d ", node.value));
node = node.right;
}
System.out.println();
System.out.print("验证反向链接:");
node = pPrevios;
while (null != node) {
System.out.print(String.format(" %d ", node.value));
node = node.left;
}
}
/**
* 中序遍历,同时调整指针
*
* @param tree
*/
static void inOrderBSTree(BSTreeNode tree) {
if (null == tree) {
return;
}
if (null != tree.left) {
inOrderBSTree(tree.left);
}
converToDoubleList(tree);
if (null != tree.right) {
inOrderBSTree(tree.right);
}
}
/**
* 调整指针
*
* @param tree
*/
static void converToDoubleList(BSTreeNode tree) {
tree.left = pPrevios;// 使当前结点的左指针指向链表的上一个结点
if (null == pPrevios) {// 若上一个结点不存在,此时双向链表不存在,因此将当前结点设为链表头结点
pHeader = tree;
} else {//
pPrevios.right = tree;
}
pPrevios = tree;// 将当前结点设为最后一个结点
}
}
class BSTreeNode {
int value;// value of node
BSTreeNode left;// left child of node
BSTreeNode right;// right child of node
public void add(int intValue) {
if (0 == value) {
value = intValue;
} else if (intValue < value) {
if (null == left) {
left = new BSTreeNode();
}
left.add(intValue);
} else if (intValue > value) {
if (null == right) {
right = new BSTreeNode();
}
right.add(intValue);
}
}
}