Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 850f1b1

Browse files
Create 1609.py
1 parent 82dfc4f commit 850f1b1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎1601-1800/1609.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /