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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
感谢大佬
[***.8.128.20]2024年04月25日 07时21分26秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Azkaban体系结构
2019-05-01
机器学习之重头戏-特征预处理
2019-05-01
synchronized底层实现及锁的升级、降级
2019-05-01
PermGen space-永久区内存溢出
2019-05-01
Maven继承和聚合
2019-05-01
Apache Kafka:优化部署的 10 种最佳实践
2019-05-01
Leetcode 35. 搜索插入位置 c#
2019-05-01
LeetCode62. 不同路径
2019-05-01
记gdb调试一次报错:Missing separate debuginfos, use: zypper install glibc-32bit-debuginfo-2.22-15.3.x86_64
2019-05-01
LeetCode242. 有效的字母异位词
2019-05-01
LeetCode83. 删除排序链表中的重复元素
2019-05-01
关于301和302重定向的理解
2019-05-01
使用java代码和jmeter脚本批量造数
2019-05-01
[9] JMeter-常用函数的使用
2019-05-01
[10] JMeter-察看结果树,你知道都有哪些功能吗?
2019-05-01
[11] JMeter-结果分析之聚合报告
2019-05-01
[12] JMeter-结果分析之图形图表
2019-05-01
[13] JMeter-详解JMeter参数化之CSV Data Set Config
2019-05-01