[LeetCode] 109. Convert Sorted List to Binary Search Tree_Medium tag: Linked List

Given 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:

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

这个题目可以利用divide and conquer的办法, 先将head 这个list的中点的前一个点找到,然后分别recursive得去判断左边的list 和右边的list,最后将中间的点作为Tree node,然后加起来即可。

T: O(n * lg(n))   # 因为是要找到中点的前一个点,所以需要用dummy node, 然后将slow 和fast 指针都移到 dummy,而不是head

code

# 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 not head: return 
        if not head.next: return TreeNode(head.val)
        dummy = ListNode(0)
        dummy.next = head
        while fast:
            if not fast.next or not fast.next.next:
                middle = slow.next
                slow.next = None
                break
            slow = slow.next
            fast = fast.next.next
        treeHead = TreeNode(middle.val)
        treeHead.left = self.sortedListToBST(head)
        treeHead.right = self.sortedListToBST(middle.next)
        return treeHead

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/10817499.html