forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
even-odd-tree.py
37 lines (34 loc) · 1006 Bytes
/
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
34
35
36
37
# Time: O(n)
# Space: O(w)
# 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 isEvenOddTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
q = [root]
is_odd = False
while q:
new_q = []
prev = None
for node in q:
if is_odd:
if node.val%2 or (prev and prev.val <= node.val):
return False
else:
if not node.val%2 or (prev and prev.val >= node.val):
return False
if node.left:
new_q.append(node.left)
if node.right:
new_q.append(node.right)
prev = node
q = new_q
is_odd = not is_odd
return True