forked from terrytong0876/LintCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvert Sorted List to Binary Search Tree.java
More file actions
87 lines (70 loc) · 1.94 KB
/
Copy pathConvert Sorted List to Binary Search Tree.java
File metadata and controls
87 lines (70 loc) · 1.94 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
M
Divide and Conquer
用快慢pointer
找到mid。
然后把root = mid.next
然后开始sortedListToBST(mid.next.next); //后半段
mid.next = null;//非常重要,要把后面拍过序的断掉
sortedListToBST(head); //从头开始的前半段
最后root.left, root.right merge一下。
```
/*
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Example
Tags Expand
Recursion Linked List
Thinking Process:
Find the middle point of the list.
Left of the mid will be left-tree, right of the mid node will be right-tree.
*/
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: a tree node
*/
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
} else if (head.next == null) {
return new TreeNode(head.val);
}
ListNode mid = findMiddle(head);
TreeNode root = new TreeNode(mid.next.val);
TreeNode right = sortedListToBST(mid.next.next);
mid.next = null;
TreeNode left = sortedListToBST(head);
root.left = left;
root.right = right;
return root;
}
public ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
```