一、实现
public class E36ConvertBSTToDeque {
private static class BinaryTreeNode{
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}
private static BinaryTreeNode convertCore(BinaryTreeNode node, BinaryTreeNode lastNode){
if (node.left != null)
lastNode = convertCore(node.left, lastNode);
node.left = lastNode;
if (lastNode != null)
lastNode.right = node;
lastNode = node;
if (node.right != null)
lastNode = convertCore(node.right, lastNode);
return lastNode;
}
public static BinaryTreeNode convert(BinaryTreeNode root){
if (root == null)
return null;
BinaryTreeNode node = convertCore(root, null);
while(node != null && node.left != null){
node = node.left;
}
return node;
}
二、测试用例
public static void main(String[] args){
int[] binarySearchTree = {10, 5, 12, 4, 7};
BinaryTreeNode root = construct(binarySearchTree, 0);
root = E36ConvertBSTToDeque.convert(root);
if (root != null) {
while (root.right!= null) {
System.out.print(root.value + " ");
root = root.right;
}
while (root != null) {
System.out.print(root.value + " ");
root = root.left;
}
}
}
private static BinaryTreeNode construct(int[] order, int index){
if (index >= order.length)
return null;
BinaryTreeNode node = new BinaryTreeNode();
node.value = order[index];
node.left = construct(order, index * 2 + 1);
node.right = construct(order, index * 2 + 2);
return node;
}