-
Notifications
You must be signed in to change notification settings - Fork 0
/
Convert Sorted List to Binary Search Tree.kt
56 lines (46 loc) · 1.16 KB
/
Convert Sorted List to Binary Search Tree.kt
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
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun sortedListToBST(head: ListNode?): TreeNode? {
return constructNode(head)
}
private fun constructNode(root: ListNode?): TreeNode? {
if (root == null) {
return null
}
var prevSlow: ListNode? = null
var slow = root
var fast = root
while (fast?.next != null && fast != null) {
prevSlow = slow
slow = slow?.next
fast = fast?.next?.next
}
prevSlow?.next = null
val value = slow?.`val` ?: 0
val currentNode = TreeNode(value)
if (slow == root) {
return currentNode
}
currentNode?.left = constructNode(root)
currentNode?.right = constructNode(slow?.next)
return currentNode
}
}