zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    bootstrap不同屏幕区分数值
    jq星星评分
    大話西遊
    HDU 5353 Average 贪心
    HDU 5358 First One 数学+尺取法
    生活感受
    HDU 4372 Count the Buildings 组合数学
    暑假集训-合训第九场
    一些资料
    多校-HDU 5351 MZL's Border 数学规律
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12823532.html
Copyright © 2011-2022 走看看