样例
树的中序遍历:1 2 3 4 5 6 7 ,转换后双向链表的遍历:1 2 3 4 5 6 7
java代码
/**
* @Description:搜索二叉树转换为双向链表
* @Author: lizhouwei
* @CreateDate: 2018/4/7 10:45
* @Modify by:
* @ModifyDate:
*/
public class Chapter2_15 {
public DoubleNode treeToDubleNode(Tree tree) {
//用队列存放将树的中序遍历
Queue<Tree> trees = new LinkedList<Tree>();
//中序遍历
recInOrder(tree, trees);
//构造双向链表
tree = trees.poll();
DoubleNode head = new DoubleNode(tree.vlaue);
DoubleNode pre = head;
DoubleNode cur = null;
while (!trees.isEmpty()) {
tree = trees.poll();
cur = new DoubleNode(tree.vlaue);
pre.next = cur;
cur.pre = pre;
pre = cur;
}
return head;
}
public void recInOrder(Tree tree, Queue<Tree> trees) {
if (tree == null) {
return;
}
recInOrder(tree.left, trees);
trees.offer(tree);
recInOrder(tree.right, trees);
}
//打印树
public void recInOrder(Tree tree) {
if (tree == null) {
return;
}
recInOrder(tree.left);
System.out.print(tree.vlaue + " ");
recInOrder(tree.right);
}
//测试
public static void main(String[] args) {
Chapter2_15 chapter = new Chapter2_15();
Tree root = new Tree(4);
root.left = new Tree(2);
root.right = new Tree(6);
root.left.left = new Tree(1);
root.left.right = new Tree(3);
root.right.left = new Tree(5);
root.right.right = new Tree(7);
chapter.recInOrder(root);
DoubleNode head = chapter.treeToDubleNode(root);
Link.printDLink(head);
}
}
class Tree {
public int vlaue;
public Tree left;
public Tree right;
public Tree(int vlaue) {
this.vlaue = vlaue;
}
}