|
| 1 | +class Solution: |
| 2 | + def isEvenOddTree(self, root): |
| 3 | + if not root: |
| 4 | + # An empty tree is considered an Even-Odd tree. |
| 5 | + return True |
| 6 | + |
| 7 | + # Use a deque for efficient queue operations. |
| 8 | + queue = deque([root]) |
| 9 | + level = 0 |
| 10 | + |
| 11 | + while queue: |
| 12 | + prev_val = None # Previous value at the current level. |
| 13 | + |
| 14 | + # Process all nodes at the current level. |
| 15 | + for _ in range(len(queue)): |
| 16 | + node = queue.popleft() |
| 17 | + |
| 18 | + # Check if the values follow the Even-Odd conditions. |
| 19 | + if (level % 2 == 0 and (node.val % 2 == 0 or (prev_val is not None and node.val <= prev_val))) or \ |
| 20 | + (level % 2 == 1 and (node.val % 2 == 1 or (prev_val is not None and node.val >= prev_val))): |
| 21 | + return False |
| 22 | + |
| 23 | + prev_val = node.val |
| 24 | + |
| 25 | + # Add children to the deque. |
| 26 | + if node.left: |
| 27 | + queue.append(node.left) |
| 28 | + if node.right: |
| 29 | + queue.append(node.right) |
| 30 | + |
| 31 | + level += 1 |
| 32 | + |
| 33 | + # All levels satisfy the conditions. |
| 34 | + return True |
0 commit comments