给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
解题思路
先将链表转为数组,数组的中间元素作为二叉搜索树的跟,该点左侧的所有元素递归取构造左子树,同理右侧的元素构造右子树,这样可以保证构造的BST是平衡的。
注意这里的二叉树的构造方法,老是忘记
# 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:
if head==None:
return None
head_list = []
# 将链表转成数组
while head!=None:
head_list.append(head.val)
head = head.next
# 使用递归构建二叉搜索树
def convert_BST(h_list):
if len(h_list)==0:
return None
n = len(h_list)
# 数组的中间值为当前子树的根节点
father_node = n // 2
p = TreeNode(h_list[father_node])
p.left = convert_BST(h_list[:father_node])
p.right = convert_BST(h_list[father_node+1:])
return p
root = convert_BST(head_list)
return root
108. 将有序数组转换为二叉搜索树
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
n = len(nums)
if n==0:
return None
# 列表中间的元素作为当前子树的根节点
father = n // 2
p = TreeNode(nums[father])
p.left = self.sortedArrayToBST(nums[:father])
p.right = self.sortedArrayToBST(nums[father+1:])
return p