Skip to content

Commit bac4113

Browse files
committed
added 0110_balanced_binary_tree.py
1 parent 53b53bd commit bac4113

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

0110_balanced_binary_tree.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
Given a binary tree, determine if it is height-balanced.
3+
4+
For this problem, a height-balanced binary tree is defined as:
5+
6+
a binary tree in which the left and right subtrees of every node
7+
differ in height by no more than 1.
8+
9+
Example 1:
10+
Input: root = [3,9,20,null,null,15,7]
11+
Output: true
12+
13+
Example 2:
14+
Input: root = [1,2,2,3,3,null,null,4,4]
15+
Output: false
16+
17+
Example 3:
18+
Input: root = []
19+
Output: true
20+
21+
Constraints:
22+
* The number of nodes in the tree is in the range [0, 5000]
23+
* -10^4 <= Node.val <= 10^4
24+
"""
25+
26+
class Solution:
27+
# O(2^n) solution, recursive
28+
def isBalanced(self, root: Optional[TreeNode]) -> bool:
29+
if root is None:
30+
return True
31+
32+
left = {}
33+
right = {}
34+
self.helper(root, left, right)
35+
36+
for k in left:
37+
if abs(left[k] - right[k]) > 1:
38+
return False
39+
40+
return True
41+
42+
def helper(self, node, l={}, r={}):
43+
if not node is None:
44+
l[node] = 0
45+
r[node] = 0
46+
47+
if not node.left is None:
48+
self.helper(node.left, l, r)
49+
l[node] = max(l[node.left], r[node.left]) + 1
50+
51+
if not node.right is None:
52+
self.helper(node.right, l, r)
53+
r[node] = max(l[node.right], r[node.right]) + 1
54+

0 commit comments

Comments
 (0)