您的位置:首页 > 编程语言 > Java开发

二叉搜索树与双向链表Java

2016-03-08 18:51 645 查看
题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的方向。

思路:在二叉搜索树中,左子结点的值总是小于父子结点的值,右子结点的值总是大于父结点的值。因此在转换成排序的双向链表时,原先指向左子节点的值调整为 链表中指向前一个结点的指针,原先指向右子结点的指针调整为链表中指向后一个结点的指针。



根结点,左子树和右子树。在把左,右子树都转换成排序的双向链表之后再和根结点连接起来,整棵二叉搜索树也就转换成了排序的双向链表。

package offer;
/**
*二叉搜索树与双向链表
*输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何结点,只能调整树中结点指针的指向。
*/
public class Convert {
public static void main(String[] args) {
int[] pre={10,6,4,8,14,12,16};
int[] inOrder = {4,6,8,10,12,14,16};
BinaryTreeNode root = RebuildBinaryTree.rebuildBinaryTree(pre, inOrder);
root.preOrder(root);
BinaryTreeNode head = convert(root);
BinaryTreeNode tail = null;
System.out.println(head==null);
while(head!=null){
System.out.print(head.val+" ");
tail = head;
head = head.right;
}
System.out.println();
while(tail!=null){
System.out.print(tail.val+" ");
tail = tail.left;
}
}

public static BinaryTreeNode convert(BinaryTreeNode root){
BinaryTreeNode lastNodeInList = null;
lastNodeInList = convertNode(root,lastNodeInList);

BinaryTreeNode headOfList = lastNodeInList;
while(headOfList!=null && headOfList.left!=null){
headOfList = headOfList.left;
}
return headOfList;
}
public static BinaryTreeNode convertNode(BinaryTreeNode node, BinaryTreeNode lastNodeInList){
if(node==null)
return null;
BinaryTreeNode current = node;
if(current.left!=null)
lastNodeInList = convertNode(current.left,lastNodeInList);
current.left = lastNodeInList;
if(lastNodeInList!=null)
lastNodeInList.right = current;
lastNodeInList = current;
if(current.right!=null)
lastNodeInList = convertNode(current.right,lastNodeInList);
return lastNodeInList;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: