码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 109 Convert Sorted List to Binary Search Tree

时间:2015-06-28 09:43:54      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

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

链表转换为BST,找到最中间的node设置为树的root,然后截断(设null),对分离的两个链表再应用这个函数设置为上一级root的left child & right child.

class Solution:
    def sortedListToBST(self, head):
        if not head:
            return None
        if not head.next:
            return TreeNode(head.val)
        a, b = head, head.next
        while b.next and b.next.next:
            a = a.next
            b = b.next.next
        root = a.next #find the mid node
        new_root = TreeNode(root.val) #set it to the root of the tree
        a.next = None #the mid node was set to null, LL -> two LLs
        new_root.left = self.sortedListToBST(head) #recall the function to the two LLs
        new_root.right = self.sortedListToBST(root.next) #to construct the children
        return new_root

 

Leetcode 109 Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/lilixu/p/4605094.html

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