Repository navigation
Expand file tree
/
Copy patheven_odd_tree.py
More file actions
61 lines (42 loc) · 1.83 KB
/
Copy patheven_odd_tree.py
File metadata and controls
61 lines (42 loc) · 1.83 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""Even Odd Tree.
A binary tree is named even-odd if it meets the following conditions:
For every even-indexed level (0, 2, 4, etc), all nodes at the level have odd integer values in strictly increasing
order (from left to right).
For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from
left to right).
Given the root of a binary tree, return `True` if the binary tree is even-odd, otherwise return `False`.
"""
from collections import deque
from src.binary_tree.tree_node import TreeNode
def even_odd_tree(root: TreeNode | None):
"""Level-order traverse the tree, validating each level against the even/odd parity and ordering rules."""
if not root:
return False
level = deque([root])
even = True
while level:
last_value = None
for _ in range(len(level)):
node = level.popleft()
if even:
if not validate_even(node, last_value):
return False
elif not validate_odd(node, last_value):
return False
last_value = node.val
if node.left:
level.append(node.left)
if node.right:
level.append(node.right)
even = not even
return True
def validate_even(node: TreeNode, last_value: int | None) -> bool:
"""Check that a node's value is odd and, on an even level, strictly greater than the previous value."""
if node.val and node.val % 2 == 0:
return False
return not (last_value and node.val <= last_value)
def validate_odd(node: TreeNode, last_value: int | None) -> bool:
"""Check that a node's value is even and, on an odd level, strictly less than the previous value."""
if node.val % 2 != 0:
return False
return not (last_value and node.val >= last_value)