Leetcode练习(Python):链表类:第109题:有序链表转换二叉搜索树:给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

题目:
有序链表转换二叉搜索树:给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。  本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。  
思路:
看到二叉树要想到用递归的思想,为了找到根节点,使用双指针法,快指针是慢指针速度的二倍,快指针到达尾部的时候,慢指针到达中间位置。
程序:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

 

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

 

class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        if not head:
            return None
        if not head.next:
            return TreeNode(head.val)
        root_tree = self.findTreeRoot(head)
        root = TreeNode(root_tree.val)
        root.left = self.sortedListToBST(head)
        root.right = self.sortedListToBST(root_tree.next)
        return root
    def findTreeRoot(self, head):
        if not head:
            return None
        if not head.next:
            return head
        index1 = head
        index2 = head
        index3 = head
        while index2 and index2.next:
            index3 = index1
            index1 = index1.next
            index2 = index2.next.next
        index3.next = None
        return index1
posted on 2020-05-03 21:24  桌子哥  阅读(681)  评论(0编辑  收藏  举报