-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path110_Balanced_Binary_Tree.py
More file actions
32 lines (29 loc) · 896 Bytes
/
Copy path110_Balanced_Binary_Tree.py
File metadata and controls
32 lines (29 loc) · 896 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
32
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
lh = self.calHeight(root.left)
rh = self.calHeight(root.right)
# check the current left & right substrees and ensure each sub-stree is also balanced
return (
abs(lh - rh) <= 1
and self.isBalanced(root.left)
and self.isBalanced(root.right)
)
def calHeight(self, root):
if not root:
return 0
else:
return (
max(self.calHeight(root.left), self.calHeight(root.right)) + 1
)