-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBalanceaBST.py
More file actions
31 lines (27 loc) · 952 Bytes
/
Copy pathBalanceaBST.py
File metadata and controls
31 lines (27 loc) · 952 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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
result = []
def inorder(node):
if node:
if node.left!=None:
inorder(node.left)
result.append(int(node.val))
if node.right!=None:
inorder(node.right)
def constructBalancedTree(arr):
if not arr:
return None
mid = len(arr)//2
root = TreeNode(arr[mid])
root.left = constructBalancedTree(arr[:mid])
root.right = constructBalancedTree(arr[mid+1:])
return root
inorder(root)
# result = [int(x.val) for x in result]
return constructBalancedTree(result)