forked from tanglu/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvertSortedListToBSTree
39 lines (35 loc) · 982 Bytes
/
ConvertSortedListToBSTree
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
public class Solution {
ListNode getLeftNodeFromList(ListNode head) {
ListNode next = head;
ListNode current = head;
ListNode pre = head;
while(next!=null) {
next = next.next;
if(next==null) {
break;
}
next = next.next;
if(next==null) {
break;
}
pre = head;
head = head.next;
}
return pre;
}
public TreeNode sortedListToBST(ListNode head) {
if(head==null) {
return null;
}
if(head.next==null) {
return new TreeNode(head.val);
}
ListNode left = getLeftNodeFromList(head);
ListNode mid = left.next;
TreeNode root = new TreeNode(mid.val);
left.next = null;
root.left = sortedListToBST(head);
root.right = sortedListToBST(mid.next);
return root;
}
}