109. 有序链表转换二叉搜索树
题目描述
解题思路
方法一:二分法建树
方法 二:利用快慢指针找到链表的中点
代码实现
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
# 二分法建树
arr = []
while head:
arr.append(head.val)
head = head.next
def build(arr, s, e):
if s > e: return
mid = s + (e - s) // 2
root = TreeNode(arr[mid])
root.left = build(arr, s, mid - 1)
root.right = build(arr, mid + 1, e)
return root
root = build(arr, 0, len(arr) - 1)
return root
def sortedListToBST1(self, head: ListNode) -> TreeNode:
# 快慢指针找中点建树
def get_median(left: ListNode, right: ListNode) -> TreeNode:
fast = slow = left
while fast != right and fast.next != right:
fast = fast.next.next
slow = slow.next
return slow
def build(left: ListNode, right: ListNode) -> TreeNode:
if left == right:
return None
mid = get_median(left, right)
root = TreeNode(mid.val)
root.left = build(left, mid)
root.right = build(mid.next, right)
return root
return build(head, None)