博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 109 Convert Sorted List to Binary Search Tree
阅读量:4582 次
发布时间:2019-06-09

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

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

链表转换为BST,找到最中间的node设置为树的root,然后截断(设null),对分离的两个链表再应用这个函数设置为上一级root的left child & right child.

class Solution:    def sortedListToBST(self, head):        if not head:            return None        if not head.next:            return TreeNode(head.val)        a, b = head, head.next        while b.next and b.next.next:            a = a.next            b = b.next.next        root = a.next #find the mid node        new_root = TreeNode(root.val) #set it to the root of the tree        a.next = None #the mid node was set to null, LL -> two LLs        new_root.left = self.sortedListToBST(head) #recall the function to the two LLs        new_root.right = self.sortedListToBST(root.next) #to construct the children        return new_root

 

转载于:https://www.cnblogs.com/lilixu/p/4605094.html

你可能感兴趣的文章
SelectQueryBuilder的用法
查看>>
android的用户定位(一)
查看>>
creat-react-app搭建的项目中按需引入antd以及配置Less和如何修改antd的主题色
查看>>
IIS安装
查看>>
html块级元素和行级元素的区别和使用
查看>>
for循环嵌套
查看>>
寒冬夜行人
查看>>
poj1151 Atlantis
查看>>
HTML页面之间的参数传递
查看>>
java面试题集锦
查看>>
scikit-learn:4.2.3. Text feature extraction
查看>>
Spring Security构建Rest服务-0800-Spring Security图片验证码
查看>>
AE待整理
查看>>
java8中规范的四大函数式接口
查看>>
宝塔apache配置
查看>>
shell脚本中使用nohup执行命令不生效
查看>>
PHP 文件上传七牛云
查看>>
gitlab 邮件服务器配置
查看>>
OFO和摩拜共享单车
查看>>
数据适配 DataAdapter对象
查看>>