首页 > 编程语言 > 详细

109.Convert Sorted List to Binary Search Tree Leetcode Python

时间:2015-02-16 09:01:19      阅读:355      评论:0      收藏:0      [点我收藏+]
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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!