Last active
May 6, 2021 14:51
-
-
Save vrat28/f80e6f7d5b09c32b9d65ae35b3244de9 to your computer and use it in GitHub Desktop.
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 { | |
var current:ListNode? | |
func sortedListToBST(_ head: ListNode?) -> TreeNode? { | |
var count = 0 | |
var curr: ListNode? = head | |
while curr != nil { | |
count += 1 | |
curr = curr?.next | |
} | |
current = head | |
let rootNode = partition_helper(1,count) | |
return rootNode | |
} | |
func partition_helper(_ left: Int, _ right:Int) -> TreeNode? { | |
guard left <= right else { return nil} | |
let mid = left + (right - left ) / 2 | |
let node = TreeNode() | |
// Inorder : Left -> Root -> Right | |
node.left = partition_helper(left, mid - 1) | |
node.val = current!.val | |
// Move the list pointer | |
current = current?.next | |
node.right = partition_helper(mid + 1, right) | |
return node | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment