博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 109. Convert Sorted List to Binary Search Tree_Medium tag: Linked List
阅读量:4594 次
发布时间:2019-06-09

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

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted linked list: [-10,-3,0,5,9],One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:      0     / \   -3   9   /   / -10  5

这个题目可以利用divide and conquer的办法, 先将head 这个list的中点的前一个点找到,然后分别recursive得去判断左边的list 和右边的list,最后将中间的点作为Tree node,然后加起来即可。

T: O(n * lg(n))   # 因为是要找到中点的前一个点,所以需要用dummy node, 然后将slow 和fast 指针都移到 dummy,而不是head

code

# 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: ListNode) -> TreeNode:        if not head: return         if not head.next: return TreeNode(head.val)        dummy = ListNode(0)        dummy.next = head        while fast:            if not fast.next or not fast.next.next:                middle = slow.next                slow.next = None                break            slow = slow.next            fast = fast.next.next        treeHead = TreeNode(middle.val)        treeHead.left = self.sortedListToBST(head)        treeHead.right = self.sortedListToBST(middle.next)        return treeHead

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/10817499.html

你可能感兴趣的文章
数据库字符集(AL32UTF8)和客户端字符集(2%)是不同的
查看>>
关于在CMD中数据库操作中文乱码问题
查看>>
机器学习之路: python 决策树分类DecisionTreeClassifier 预测泰坦尼克号乘客是否幸存...
查看>>
R语言做正态性检验
查看>>
linux用户组管理
查看>>
Console-算法[for]-输出等腰三角形
查看>>
随机数产生方法小知识点
查看>>
Angular2.js——表单(上)
查看>>
Programming With Objective-C---- Introduction ---- Objective-C 学习(一)
查看>>
正则表达式语法大全
查看>>
DateUtils
查看>>
pb开发的客户端,使用oracle 9i客户端 提示oci.dll could not be loaded
查看>>
wordpress调用指定post type文章怎么操作
查看>>
magento开发手册之目录结构
查看>>
换个红圈1微信头像恶搞一下好友
查看>>
javascript学习_廖大_20170218
查看>>
bzoj2038: [2009国家集训队]小Z的袜子(hose) 莫队
查看>>
火车头采集基本使用
查看>>
MYSQL中插入数据以及修改数据的部分方法
查看>>
unity中遍历动画得到动画名字和动画数量
查看>>