LintCode Q177 Convert Sorted Array to Binary Search Tree With Minimal Height in Python

  • Jinhai ZHOU
  • 3 Minutes
  • 2016年11月12日
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
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param A: a list of integer
@return: a tree node
"""
def sortedArrayToBST(self, A):
# write your code here
return self.toBST(A)
def toBST(self, A):
if len(A) == 0:
return
if len(A) == 1:
return TreeNode(A[0])
# len(A) >= 2
mid = len(A)/2
this = TreeNode(A[mid])
this.left = self.toBST(A[:mid])
this.right = self.toBST(A[mid+1:])
return this
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。