-
Notifications
You must be signed in to change notification settings - Fork 58
/
Day17.java
100 lines (77 loc) · 1.66 KB
/
Day17.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package com.offer;
/**
* 二叉搜索熟转换成双向链表 用中序遍历的方式,刚好满足从小到大的排序特点。
* @author kexun
*
*/
public class Day17 {
public static void main(String[] args) {
Day17 d = new Day17();
Node header = d.new Node(10);
Node node1 = d.new Node(6);
Node node2 = d.new Node(4);
Node node3 = d.new Node(8);
Node node4 = d.new Node(14);
Node node5 = d.new Node(12);
Node node6 = d.new Node(16);
header.left = node1;
header.right = node4;
node1.left = node2;
node1.right = node3;
node4.left = node5;
node4.right = node6;
Node list = d.convert(header);
d.printList(list);
}
/**
* 二叉树节点
* @author kexun
*
*/
class Node {
public int data;
public Node left;
public Node right;
public Node(int data) {
this.data = data;
}
}
public Node convert(Node node) {
Node tail = tree2List(node);
while (tail.left != null) {
tail = tail.left;
}
return tail;
}
/**
* 通过递归调用, 中序遍历搜素二叉树的方式,把二叉树转变成排序的双向链表
* @param node
* @return
*/
public Node tree2List(Node node) {
if (node == null)
return null;
if (node.left != null) {
Node left = tree2List(node.left);
node.left = left;
left.right = node;
}
if (node.right != null) {
Node right = tree2List(node.right);
node.right = right;
right.left = node;
return right;
}
return node;
}
/**
* 从头打印双向链表
* @param node
*/
public void printList(Node node) {
while (node != null) {
System.out.print(node.data+",");
node = node.right ;
}
}
}