-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedListToBST.java
More file actions
69 lines (62 loc) · 1.54 KB
/
Copy pathSortedListToBST.java
File metadata and controls
69 lines (62 loc) · 1.54 KB
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
package tree;
import linkedList.ListNode;
import org.junit.Test;
import java.util.ArrayList;
/**
* @Author: wei1
* @Date: Create in 2019/1/28 23:33
* @Description:
*/
public class SortedListToBST {
@Test
public void test() {
ListNode head = new ListNode(1);
// head.next = new ListNode(2);
// head.next.next = new ListNode(3);
TreeNode treeNode = sortedListToBST(head);
ArrayList arrayList;
int[] i;
String s;
}
public TreeNode sortedListToBST(ListNode head) {
if(head==null){
return null;
}
TreeNode root = dfs(head);
print(root);
return root;
}
public void print(TreeNode root) {
if (root == null) {
return;
}
print(root.left);
System.out.print(root.val+" ");
print(root.right);
}
public TreeNode dfs(ListNode head){
if(head==null){
return null;
}
if (head.next == null) {
return new TreeNode(head.val);
}
ListNode node = getMid(head);
TreeNode tree = new TreeNode(node.val);
tree.left = dfs(head);
tree.right = dfs(node.next);
return tree;
}
public ListNode getMid(ListNode head) {
ListNode fast = head;
ListNode slow = head;
ListNode temp = head;
while(fast!=null&&fast.next!=null){
fast = fast.next.next;
temp = slow;
slow = slow.next;
}
temp.next = null;
return slow;
}
}