leetcode 刷题108109
发布日期:2021-07-01 02:15:32 浏览次数:2 分类:技术文章

本文共 1836 字,大约阅读时间需要 6 分钟。

在这里插入图片描述

在这里插入图片描述

# Definition for a  binary tree node# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    def sortedArrayToBST(self, num):        if not num:            return None        mid = len(num) // 2        root = TreeNode(num[mid])        root.left = self.sortedArrayToBST(num[:mid])        root.right = self.sortedArrayToBST(num[mid+1:])        return root

在这里插入图片描述

在这里插入图片描述

# 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 = Noneclass Solution:    def sortedListToBST(self,head):        cnt = 0        copy = head        while head is not None:            cnt+=1            head = head.next         return self.constructBST_fromList(copy,cnt)[0]                    def constructBST_fromList(self,begin,length):        if length==0:            return None,begin        mid = length//2        left,cur = self.constructBST_fromList(begin,mid)        node = TreeNode(cur.val)        node.left = left        right,cur = self.constructBST_fromList(cur.next,length-mid-1)        node.right = right        return node,cur

class Solution(object):        def sortedListToBST(self, head):        if not head:            return                if not head.next:            return TreeNode(head.val)        fast = head        slow = None        while fast and fast.next:            fast = fast.next.next            slow = head if slow is None else slow.next        node = TreeNode(slow.next.val)        tmp = slow.next.next        slow.next = None        node.left = self.sortedListToBST(head)        node.right = self.sortedListToBST(tmp)        return node

转载地址:https://maoli.blog.csdn.net/article/details/90723458 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:leetcode 刷题 110 111
下一篇:随机森林算法

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月25日 07时21分26秒