码迷,mamicode.com
首页 > 编程语言 > 详细

109.Convert Sorted List to Binary Search Tree Leetcode Python

时间:2015-02-16 09:04:34      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:linkedlist   random   leetcode   python   

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)
        


109.Convert Sorted List to Binary Search Tree Leetcode Python

标签:linkedlist   random   leetcode   python   

原文地址:http://blog.csdn.net/hyperbolechi/article/details/43847739

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!