zoukankan      html  css  js  c++  java
  • 【leetcode】:109. 有序链表转换二叉搜索树

    题目如下,这里做一个记录:

     思路:

    1.首先使用快慢指针知道中点

    2.然后使用递归得到avl平衡二叉树,因为中点作为root后,正好可以满足二叉搜索树的性质,也就是right node一定比left node更大,同时也可以满足avl平衡二叉树的性质,左右两边最多相差一个node。

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def sortedListToBST(self, head: ListNode) -> TreeNode:
            if not head:
                return None
            elif not head.next:
                return TreeNode(head.val)
            
            pre, slow, fast = None, head, head
            while fast and fast.next:
                pre = slow
                slow = slow.next
                fast = fast.next.next
            #这个pre在这里的作用是什么?
            #print(slow.val)
            #找到中点,只需要使用经典的快慢指针即可。同时为了防止环的出现, 我们需要斩断指向 mid 的 next 指针,因此需要记录一下中点前的一个节点,这只需要用一个变量 pre 记录即可。
            #因为pre和slow共有地址,因此pre.next=none,则slow.next=none too!
            root = TreeNode(slow.val)
            pre.next = None
    
            root.left = self.sortedListToBST(head)
            root.right = self.sortedListToBST(slow.next)
            return root

    得解!

    问题,本题目很经典,但是实在是不知道这个pre node的作用是什么?因为我即使不使用pre,直接断开slow到mid的指针,程序则会报错,太奇怪了。。。

  • 相关阅读:
    css3 preserve-3d 的理解 注意IOS上的兼容
    javascript JSMpeg.js 播放视频解决不用全屏也能播放(也支持自动播放哦)
    linux写系统服务的方法
    mysql connect refuse解决方法
    SQLite-CONSTRAINTS(约束)
    Java集合
    自定义一个简单的SegmentedControl
    symbolicatecrash解析crash文件
    django应用的测试
    WordPress调用page页面内容方法
  • 原文地址:https://www.cnblogs.com/geeksongs/p/15192186.html
Copyright © 2011-2022 走看看