-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path108.py
88 lines (76 loc) · 2.43 KB
/
108.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'''
108. Convert Sorted Array to Binary Search Tree
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Hi, here's your problem today. This problem was recently asked by LinkedIn:
Given a sorted list of numbers, change it into a balanced binary search tree.
You can assume there will be no duplicate numbers in the list.
Given an array where elements are sorted in ascending order,
convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as
a binary tree in which the depth of the two subtrees of every node
never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5],
which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
'''
from typing import *
from collections import deque
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self):
# level-by-level pretty-printer
nodes = deque([self])
answer = ''
while len(nodes):
node = nodes.popleft()
if not node:
continue
answer += str(node.value) + ' '
nodes.append(node.left)
nodes.append(node.right)
return answer
class IndexSolution:
def sortedArrayToBST(self, nums: List[int], left=None, right=None) -> TreeNode:
if not nums:
return None
if left is None and right is None:
left = 0
right = len(nums)-1
if left>right:
return None
mid = left + (right-left) // 2
node = TreeNode(nums[mid])
node.left = self.sortedArrayToBST(nums, left, mid-1)
node.right = self.sortedArrayToBST(nums, mid+1, right)
return node
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums:
return None
mid = len(nums) // 2
node = TreeNode(nums[mid])
node.left = self.sortedArrayToBST(nums[:mid])
node.right = self.sortedArrayToBST(nums[mid+1:])
return node
print(Solution().sortedArrayToBST([1, 2, 3, 4, 5, 6, 7]))
# 4261357
# 4
# / \
# 2 6
#/ \ / \
#1 3 5 7
print(Solution().sortedArrayToBST([-10,-3,0,5,9]))
# 0
# / \
# -3 9
# / /
#-10 5