[109][中等][DFS][双指针] 有序链表转换二叉搜索树
题目描述
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5解题思路
转成数组
快慢指针(双指针)
相关题目
最后更新于
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5最后更新于
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
nums = []
current = head
while current is not None:
nums.append(current.val)
current = current.next
n = len(nums)
def get_root(l, r):
if l > r:
return None
mid = (l + r) // 2
root = TreeNode(nums[mid])
root.left = get_root(l, mid - 1)
root.right = get_root(mid + 1, r)
return root
return get_root(0, n - 1)class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
def get_root(pointer):
if pointer is None:
return None
if pointer.next is None:
return TreeNode(pointer.val)
fast, slow, pre = pointer, pointer, None
while fast is not None and fast.next is not None:
fast = fast.next.next
pre = slow
slow = slow.next
root = TreeNode(slow.val)
pre.next = None # 切断左子链与后面的连接, 进入递归
root.left = get_root(pointer)
root.right = get_root(slow.next)
return root
return get_root(head)