-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLC109.java
96 lines (80 loc) · 2.37 KB
/
LC109.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
/*
109. Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the
depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private ListNode head;
private int findSize(ListNode head)
{
ListNode ptr = head;
int c = 0;
while (ptr != null)
{
ptr = ptr.next;
c += 1;
}
return c;
}
private TreeNode convertListToBST(int l, int r)
{
// Invalid case
if (l > r) {
return null;
}
int mid = (l + r) / 2;
// First step of simulated inorder traversal. Recursively form
// the left half
TreeNode left = this.convertListToBST(l, mid - 1);
// Once left half is traversed, process the current node
TreeNode node = new TreeNode(this.head.val);
node.left = left;
// Maintain the invariance mentioned in the algorithm
this.head = this.head.next;
// Recurse on the right hand side and form BST out of them
node.right = this.convertListToBST(mid + 1, r);
return node;
}
public TreeNode sortedListToBST(ListNode head)
{
// Get the size of the linked list first
int size = this.findSize(head);
this.head = head;
// Form the BST now that we know the size
return convertListToBST(0, size - 1);
}
}