Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (55.6k points)

Can anyone tell me how to convert the linked list to a list in python?

1 Answer

0 votes
by (119k points)

Here is how you can convert a sorted Single Linked List to a List. Then, convert that to a Binary Search Tree:

# Definition for singly-linked list.

# class ListNode(object):

#     def __init__(self, x):

#         self.val = x

#         self.next = None

 

# 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 sortedListToBST(self, head):

        """

        :type head: ListNode

        :rtype: TreeNode

        """

        sll_list = self.linkedListToList(head)

        def convert(left, right):

            if left > right:

                return None

 

            mid = (left + right) // 2

            node = TreeNode(sll_list[mid])

            node.left = convert(left, mid -  1)

            node.right = convert(mid + 1, right)

            return node

        return convert(0, len(sll_list) - 1)   

    def linkedListToList(self, head):

        if not head:

            return []

        pointer = head

        sll_list = []

        while pointer:

            sll_list.append(pointer.val)

            pointer = pointer.next

        return sll_list

I recommend enrolling in this Python Course by Intelllipaat to learn Python.

Also, you can watch this video on linked list in Python:

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 30, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
1 answer
asked Oct 30, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
1 answer

Browse Categories

...