-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path108.py
More file actions
33 lines (27 loc) · 822 Bytes
/
108.py
File metadata and controls
33 lines (27 loc) · 822 Bytes
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
'''
108. Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order,
convert it to a height balanced BST.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 130 - 150 ms
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
root = TreeNode(None)
return self.help(nums, root)
def help(self, nums, root):
if (not nums):
return None
root = TreeNode(nums[len(nums)/2])
root.left = self.help(nums[0 : len(nums)/2], root)
root.right = self.help(nums[(len(nums) / 2 + 1) : ], root)
return root