[Leetcode]Convert Sorted List to Binary Search Tree
来源:互联网 发布:Python2.7图形编程 编辑:程序博客网 时间:2024/05/29 06:41
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
把一个有序的链表转换成一颗二分查找树 ~ 刚开始用了一种比较naive的写法,虽然能AC,但是效率很慢,因为每次递归的时候都要遍历链表获得中间节点 ~ 时间复杂度是O(NlogN), This is because each level of recursive call requires a total of N/2 traversal steps in the list, and there are a total of lg N number of levels (ie, the height of the balanced tree).
class Solution: # @param head, a list node # @return a tree node def sortedListToBST(self, head): if head is None: return None if head.next is None: return TreeNode(head.val) fast, slow, prev = head, head, None while fast != None and fast.next != None: prev = slow fast, slow = fast.next.next, slow.next if prev != None: prev.next = None root = TreeNode(slow.val) root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(slow.next) return root
class Solution: # @param head, a list node # @return a tree node def sortedListToBST(self, head): if head is None: return None curr, length = head, 0 while curr != None: curr, length = curr.next, length + 1 self.head = head return self.sortedRecur(0, length - 1) def sortedRecur(self, start, end): if start > end: return None mid = (start + end) / 2 left = self.sortedRecur(start, mid - 1) root = TreeNode(self.head.val) root.left = left self.head = self.head.next root.right = self.sortedRecur(mid + 1, end) return root
0 0
- 【LeetCode】Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree
- LeetCode[Tree]: Convert Sorted List to Binary Search Tree
- [leetcode][list][dfs] Convert Sorted List to Binary Search Tree
- LeetCode: Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- LeetCode : Convert Sorted List to Binary Search Tree
- [Leetcode] Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Balanced Binary Search Tree
- [LeetCode] Convert Sorted List to Binary Search Tree
- leetcode 66: Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode:Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- [Leetcode]Convert Sorted List to Binary Search Tree
- [leetcode]Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Binary Search Tree
- DDR controller driver
- 使用Sublime经验分享
- Spring cache 缓存介绍
- HDU4546 比赛难度 (优先队列)
- Java学习之Iterator(迭代器)的一般用法
- [Leetcode]Convert Sorted List to Binary Search Tree
- hdu 2013
- 实体实例的键成员的值已更改。实体键成员不能更改。
- Apache 使用localhost(127.0.0.1)可以访问,使用本机局域网IP(192.168.1.*)不能访问
- ios 使用Safari浏览器跳转打开、唤醒app
- HDFS命令
- JAVA WeakReference
- asp.net web api
- hdu 2014