-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path110_Balanced_Binary_Tree.py
More file actions
42 lines (34 loc) · 1.06 KB
/
110_Balanced_Binary_Tree.py
File metadata and controls
42 lines (34 loc) · 1.06 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
# Author: cym
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
que = [root]
while len(que) != 0:
node = que[0]
que = que[1:]
left_depth = self.treeDepth(node.left)
right_depth = self.treeDepth(node.right)
if abs(left_depth - right_depth) > 1:
return False
if node.left is not None:
que.append(node.left)
if node.right is not None:
que.append(node.right)
return True
def treeDepth(self, root):
if root is None:
return 0
left_depth = 1 + self.treeDepth(root.left)
right_depth = 1 + self.treeDepth(root.right)
return max(left_depth, right_depth)