-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathq0110.py
More file actions
37 lines (31 loc) · 984 Bytes
/
q0110.py
File metadata and controls
37 lines (31 loc) · 984 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
33
34
35
36
37
# Definition for a binary tree node.
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
map = {}
def depth(node):
if not node:
return 0
if node in map:
return map[node]
left = depth(node.left)
right = depth(node.right)
map[node] = max(left, right) + 1
return map[node]
bfs_queue = deque([])
if root:
bfs_queue.append(root)
while bfs_queue:
node = bfs_queue.popleft()
if abs(depth(node.left) - depth(node.right)) > 1:
return False
if node.left:
bfs_queue.append(node.left)
if node.right:
bfs_queue.append(node.right)
return True