-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path110.balanced-binary-tree.python2.py
More file actions
37 lines (27 loc) · 1.12 KB
/
Copy path110.balanced-binary-tree.python2.py
File metadata and controls
37 lines (27 loc) · 1.12 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
# @leet start
# 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: Optional[TreeNode]
:rtype: bool
"""
def checkHeight(node):
if not node:
return 0 # Высота пустого дерева = 0
left_height = checkHeight(node.left)
if left_height == -1:
return -1 # Левое поддерево несбалансировано
right_height = checkHeight(node.right)
if right_height == -1:
return -1 # Правое поддерево несбалансировано
if abs(left_height - right_height) > 1:
return -1 # Текущий узел несбалансирован
return max(left_height, right_height) + 1 # Возвращаем высоту текущего узла
return checkHeight(root) != -1
# @leet end