首页 > 其他 > 详细

Leetcode 109 Convert Sorted List to Binary Search Tree

时间:2015-06-28 09:41:43      阅读:116      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!