-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path1382-balance-a-binary-search-tree.py
41 lines (31 loc) · 1.15 KB
/
1382-balance-a-binary-search-tree.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
# time complexity: O(n)
# space complexity: O(n)
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
inorderList = []
self.Traversal(root, inorderList)
return self.createBalancedBst(inorderList, 0, len(inorderList) - 1)
def Traversal(self, root: TreeNode, inorder: list):
if not root:
return
self.Traversal(root.left, inorder)
inorder.append(root.val)
self.Traversal(root.right, inorder)
def createBalancedBst(self, inorder: list, start: int, end: int) -> TreeNode:
if start > end:
return None
mid = start + (end - start) // 2
leftSubtree = self.createBalancedBst(inorder, start, mid - 1)
rightSubtree = self.createBalancedBst(inorder, mid + 1, end)
node = TreeNode(inorder[mid], leftSubtree, rightSubtree)
return node
root = TreeNode(1)
root.right = TreeNode(2)
root.right.right = TreeNode(3)
root.right.right.right = TreeNode(4)
print(Solution().balanceBST(root))