Convert Sorted List to Binary Search Tree Total Accepted: 32343 Total Submissions: 117376 My Submissions Question Solution
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST
这题和convert array to binary search tree不同点在与LinkedList 没有random access所以要想找到中点只能利用fast 和slow pointer来查找。
这种方法比直接把linkedlist转成array要慢。
代码如下:
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a list node
# @return a tree node
def convert(self,head,tail):
if head==tail:
return None
if head.next==tail:
return TreeNode(head.val)
mid=head
fast=head
while fast!=tail and fast.next!=tail:
fast=fast.next.next
mid=mid.next
node=TreeNode(mid.val)
node.left=self.convert(head,mid)
node.right=self.convert(mid.next,tail)
return node
def sortedListToBST(self, head):
return self.convert(head,None)