Created
May 6, 2021 14:29
-
-
Save vrat28/6041b0c440aeb2bb9f58a93c9fe8fddb to your computer and use it in GitHub Desktop.
LinkedList to Binary Search Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func sortedListToBST(_ head: ListNode?) -> TreeNode? { | |
var sortedList = [Int]() | |
var current:ListNode? = head | |
while let node = current { | |
sortedList.append(node.val) | |
current = node.next | |
} | |
let rootNode = partition_helper(sortedList, 0, sortedList.count - 1) | |
return rootNode | |
} | |
func partition_helper(_ list:[Int], _ left: Int, _ right:Int) -> TreeNode? { | |
guard left <= right else { return nil} | |
let mid = left + (right - left ) / 2 | |
let node = TreeNode(list[mid]) | |
node.left = partition_helper(list, left, mid - 1) | |
node.right = partition_helper(list,mid + 1, right) | |
return node | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment