卖萌的弱渣

I am stupid, I am hungry.

Convert Sorted List to Balanced BST

Convert Sorted List to Balanced BST

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Example

1
2
3
               2
1->2->3  =>   / \
             1   3

Solution

  • Time: O(n2)
  • We dont have to find the middle node in each interation.
  • if you change the input parameters and add left,right and write another helper func to help iteration, could get O(N)
(Convert-Sorted-List-to-BST.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
Definition of ListNode

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next

Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
class Solution:
    """
    @param head: The first node of linked list.
    @return: a tree node
    """
    def sortedListToBST(self, head):
        # write your code here
        if head == None:
            return None
        if head.next == None:
            new_node = TreeNode(head.val)
            return new_node
        # find middle
        dummy = ListNode(0,None)
        dummy.next = head

        fast_node = dummy
        slow_node = dummy

        while fast_node != None and fast_node.next != None:
            fast_node = fast_node.next.next
            prev_node = slow_node
            slow_node = slow_node.next

        # create the middle node
        middle_node = TreeNode(slow_node.val)
        middle_node.right = self.sortedListToBST(slow_node.next)
        prev_node.next = None
        middle_node.left = self.sortedListToBST(dummy.next)

        return middle_node