【LeetCode 中等题】52-有序链表转二叉搜索树

题目描述:给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

解法1。链表有序,说明是中序遍历的结果,利用快慢指针找到链表中点,然后切断左和中点-右的联系,每次递归找子链的中点,注意边界条件。思路和从有序链表里构建二叉树是一样的思路。

class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        if not head:
            return
        if not head.next:
            return TreeNode(head.val)
        root_node = self.findRoot(head)
        root = TreeNode(root_node.val)
        root.left = self.sortedListToBST(head)
        root.right = self.sortedListToBST(root_node.next)
        return root
        
    
    def findRoot(self, head):
        if not head or not head.next:
            return head
        fast = head
        slow = head
        pre = head
        while fast and fast.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next
        pre.next = None
        return slow

参考链接:http://www.cnblogs.com/grandyang/p/4295618.html

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/85993547
今日推荐