forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
26 lines (25 loc) · 832 Bytes
/
Solution.py
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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
def buildBST(nums, start, end):
if start > end:
return None
mid = (start + end) >> 1
return TreeNode(
nums[mid], buildBST(nums, start, mid - 1), buildBST(nums, mid + 1, end)
)
nums = []
while head:
nums.append(head.val)
head = head.next
return buildBST(nums, 0, len(nums) - 1)