Given the head
of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Input: head = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example 2:
Input: head = [] Output: []
Constraints:
- The number of nodes in
head
is in the range[0, 2 * 104]
. -105 <= Node.val <= 105
题目大意是把一个排好序的单向链表转换成一棵高度平衡的二叉搜索树。所谓高度平衡就是树里任意一个节点的左右子树的高度相差不超过1。
要使一棵二叉搜索树的高度平衡需要满足两个条件,根节点的左子树和右子树都是高度平衡的,并且左右子树的高度相差不超过1。而对于一个排好序的链表,如果我们选取中间节点作为二叉搜索树的根节点,中间节点之前的所有节点值都小于中间节点值可以作为左子树,中间节点之后的所有节点值都大于中间节点值可以作为右子树。又由于是从中间分开,那么前后两部分节点个数相差不超过1,如果前后两部分都转化成平衡的二叉搜索树,那么它们的高度差一定不会超过1,这样左右两棵平衡二叉搜索子树与中间节点为根节点构成的二叉搜索树肯定是平衡的。
获取中间节点可以使用快慢指针法。把中间节点的前后两部分形成两个子链表(别忘了前面部分的最后一个节点next指向空)转换成平衡二叉搜索树可以使用递归法,直到只剩一个节点或空节点直接返回。
# 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]:
if not head:
return None
if not head.next:
return TreeNode(head.val)
pre, p1, p2 = None, head, head
while p2 and p2.next:
pre = p1
p1 = p1.next
p2 = p2.next.next
root = TreeNode(p1.val)
pre.next = None
root.left = self.sortedListToBST(head)
root.right = self.sortedListToBST(p1.next)
return root