Convert Sorted List to Binary Search Tree
来源:互联网 发布:mac os沙盒 编辑:程序博客网 时间:2024/05/16 06:03
题目:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:
具体思路即为,每次查找到中间的节点,将其作为树的根节点,以该点切分,其左侧以及右侧皆采用此方法,最终即构建出来所需的树。边界条件需要多加注意。此题思路挺好,须多多思考!
# 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 = None
class Solution:
# @param {ListNode} head
# @return {TreeNode}
def sortedListToBST(self, head):
def sortedListToBST_new(head,length):
if length==0:
return None
elif length==1:
return TreeNode(head.val)
else:
tmp = head
for i in range(length/2):
tmp = tmp.next
root = TreeNode(tmp.val)
root.left = sortedListToBST_new(head,length/2)
root.right = sortedListToBST_new(tmp.next,length-length/2-1)
return root
p = head
length = 0
while p:
length += 1
p = p.next
return sortedListToBST_new(head,length)
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- convert sorted list to binary search tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- 优先队列及最小堆最大堆
- Hadoop集群(第10期)_MySQL关系数据库
- HDU -- 1298 T9 (Trie 树+dfs)
- 毕业课题之---HOG+SVM的一个研究过程
- 中国国产汽车的悲哀
- Convert Sorted List to Binary Search Tree
- Python Show-Me-the-Code 第 0023 题 Web留言簿应用
- Branch分支结构
- HDU--2851(最短路)
- 初识JAVA4
- TangIDE游戏开发之70行代码实现打地鼠
- [SQL SERVER][災難復原] LDF檔毀損導致資料庫進入復原暫止
- Js数组的操作push,pop,shift,unshift等方法详细介绍
- ISO8583报文协议