LintCode Q106 Convert Sorted List to Balanced BST in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2017年1月16日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param head: The first node of linked list.
@return: a tree node
"""
def sortedListToBST(self, head):
# write your code here
if head is None:
return None
runner = head
previous = None
current = head
while runner and runner.next:
previous = current
current = current.next
runner = runner.next.next
current_node = TreeNode(current.val)
if previous is not None:
previous.next = None
current_node.left = self.sortedListToBST(head)
if current.next is not None:
current_node.right = self.sortedListToBST(current.next)
return current_node
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。