题目:
给定一个单链表的头节点
head
,其中的元素 按升序排序 ,将其转换为高度平衡的二叉搜索树。本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差不超过 1。
来源:力扣(LeetCode)
链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
示例:
示例 1:
输入:head = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:一个可能的答案是[0,-3,9,-10,null,5],它表示所示的高度平衡的二叉搜索树。
示例 2:输入:head = []
输出:[]
解法:
链表转成列表,接着用递归解。
代码:
# 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: Optional[ListNode]) -> Optional[TreeNode]:def bst(trees, pre, left_or_right):if len(trees) == 0:returnmid = (len(trees) - 1) // 2if left_or_right == 0:pre.left = node = TreeNode(trees[mid])else:pre.right = node = TreeNode(trees[mid])bst(trees[:mid], node, 0)bst(trees[mid + 1:], node, 1)nums = []while head:nums.append(head.val)head = head.nextif len(nums) == 0:return Nonemid = (len(nums) - 1) // 2root = TreeNode(nums[mid])bst(nums[:mid], root, 0)bst(nums[mid + 1:], root, 1)return root