-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL110_balanced_binary_tree.py
More file actions
150 lines (119 loc) · 3.85 KB
/
Copy pathL110_balanced_binary_tree.py
File metadata and controls
150 lines (119 loc) · 3.85 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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""
Leetcode link: https://leetcode.com/problems/balanced-binary-tree
"""
from typing import Optional
from datastructures import TreeNode
from test import evaluate_test_cases
class Solution:
"""
Steps for solving the problem
1.State the problem in own words. Identify input/output formats
2.Figure out example input/output values covering edge cases as well
3.Write plain English pseudo code
4.Implement, test and fix issues
5.Analyze complexity and efficiency
6.Fix complexities and efficiencies, repeat 3-6
Quesion:
Given a binary tree, determine if it is height-balanced.
height-balanced = A height-balanced binary tree is a binary tree in which
the depth of the two subtrees of every node never differs by more than one.
Constraints:
a. The number of nodes in the tree is in the range [0, 5000].
b. -104 <= Node.val <= 104
Problem:
For a given binary tree, check if its height balanced. ie. check if depth of both
subtrees of all nodes don't differ by more than one.
"""
def isBalanced(self, root: Optional[TreeNode]) -> bool:
"""
Solution:
1. for each node,
a. get right max height
b. get left max height
c. check if left-right > 1
d. if yes, immediate break and return False
e. else return 1+max(left,right)
2. return True at the end
"""
"""
Solution breaking out with exception when finding a node with
unbalanced subtrees
"""
# def dfs(root):
# if root is None:
# return 0
# left = dfs(root.left)
# right = dfs(root.right)
# print(f'{left=},{right=}')
# if abs(left-right) > 1:
# raise Exception("not balanced")
# return 1+max(left,right)
# try:
# dfs(root)
# except:
# return False
# return True
"""
Without throwing exception, but completely traversing
the whole tree, even after encountering a False
"""
def dfs(root):
if root is None:
return [True, 0]
left = dfs(root.left)
right = dfs(root.right)
balanced = left[0] and right[0] and abs(left[1]-right[1]) <=1
return [balanced, 1+max(left[1],right[1])]
return dfs(root)[0]
def load_test_cases():
"""
List of identified test cases covering standard, edge cases:
1. empty root
2. single node
3. balanced both sides
4. balanced one side has +1 depth
5. non-balanced root
6. non-balanced child
"""
test_cases = []
# 1. empty root
test_cases.append({
'input': {
'root': TreeNode.parse_tuple(()),
}, 'output': True
})
# 2. single node
test_cases.append({
'input': {
'root': TreeNode.parse_tuple((1)),
}, 'output': True
})
# 3. balanced both sides
test_cases.append({
'input': {
'root': TreeNode.parse_tuple((2,1,3)),
}, 'output': True
})
# 4. balanced one side has +1 depth
test_cases.append({
'input': {
'root': TreeNode.parse_tuple((2,1,(4,3,5))),
}, 'output': True
})
# 5. non-balanced root
test_cases.append({
'input': {
'root': TreeNode.parse_tuple((((6,4,7),2,5),1,3)),
}, 'output': False
})
# 6. non-balanced child
test_cases.append({
'input': {
'root': TreeNode.parse_tuple(((((None,6,8),4,7),2,5),1,3)),
}, 'output': False
})
return test_cases
if __name__ == "__main__":
test_cases = load_test_cases()
solution = Solution()
evaluate_test_cases(solution.isBalanced, test_cases)