-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathBalanced Binary Tree
More file actions
56 lines (33 loc) · 1.11 KB
/
Copy pathBalanced Binary Tree
File metadata and controls
56 lines (33 loc) · 1.11 KB
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
# Checking if a binary tree is CalculateHeight balanced in Python
# CreateNode creation
class CreateNode:
def __init__(self, item):
self.item = item
self.left = self.right = None
# Calculate height
class CalculateHeight:
def __init__(self):
self.CalculateHeight = 0
# Check height balance
def is_height_balanced(root, CalculateHeight):
left_height = CalculateHeight()
right_height = CalculateHeight()
if root is None:
return True
l = is_height_balanced(root.left, left_height)
r = is_height_balanced(root.right, right_height)
CalculateHeight.CalculateHeight = max(
left_height.CalculateHeight, right_height.CalculateHeight) + 1
if abs(left_height.CalculateHeight - right_height.CalculateHeight) <= 1:
return l and r
return False
CalculateHeight = CalculateHeight()
root = CreateNode(1)
root.left = CreateNode(2)
root.right = CreateNode(3)
root.left.left = CreateNode(4)
root.left.right = CreateNode(5)
if is_height_balanced(root, CalculateHeight):
print('The tree is balanced')
else:
print('The tree is not balanced')