-
Notifications
You must be signed in to change notification settings - Fork 0
/
1609. Even Odd Tree.py
33 lines (26 loc) · 1000 Bytes
/
1609. Even Odd Tree.py
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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
queue = deque([root])
level = 0
while queue:
prev_val = None
for _ in range(len(queue)):
node = queue.popleft()
if (level % 2 == 0 and (node.val % 2 == 0 or (prev_val is not None and node.val <= prev_val))) or \
(level % 2 == 1 and (node.val % 2 == 1 or (prev_val is not None and node.val >= prev_val))):
return False
prev_val = node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
level += 1
return True