Even Odd Tree - Problem
Imagine a binary tree where each level follows a special alternating pattern - like floors in a magical building where each floor has its own unique rules!
A binary tree is called an Even-Odd Tree if it satisfies these enchanting conditions:
- Even-indexed levels (0, 2, 4, ...): All node values must be odd numbers and arranged in strictly increasing order from left to right
- Odd-indexed levels (1, 3, 5, ...): All node values must be even numbers and arranged in strictly decreasing order from left to right
Given the root of a binary tree, determine if it qualifies as an Even-Odd Tree. Return true if it does, false otherwise.
Example: Level 0 (even): [1, 5, 9] โ (odd, increasing) | Level 1 (odd): [4, 2] โ (even, decreasing)
Input & Output
example_1.py โ Valid Even-Odd Tree
$
Input:
root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
โบ
Output:
true
๐ก Note:
Level 0 (even): [1] - odd values in increasing order โ. Level 1 (odd): [10,4] - even values in decreasing order โ. Level 2 (even): [3,7,9] - odd values in increasing order โ. Level 3 (odd): [12,8,6,2] - even values in decreasing order โ.
example_2.py โ Invalid Parity
$
Input:
root = [5,4,2,3,3,7]
โบ
Output:
false
๐ก Note:
Level 1 (odd): [4,2] - contains even values but not in decreasing order (4 > 2, but we need strictly decreasing). Actually, this should be decreasing, but level 2 has [3,3,7] which violates strictly increasing (3 == 3).
example_3.py โ Single Node Tree
$
Input:
root = [5]
โบ
Output:
true
๐ก Note:
Single node tree with root value 5 (odd) at level 0 (even). Since level 0 requires odd values and there's only one node, the increasing order constraint is trivially satisfied.
Constraints
- The number of nodes in the tree is in the range [1, 105]
- 1 โค Node.val โค 106
- Level indexing starts from 0 (root is at level 0)
- Tree nodes can have null children
Visualization
Tap to expand
Understanding the Visualization
1
Initialize BFS
Start with root node at level 0, prepare queue for level-order traversal
2
Process Each Level
For each level, process all nodes left to right while tracking constraints
3
Validate Parity
Even levels must have odd values, odd levels must have even values
4
Validate Ordering
Even levels need strictly increasing, odd levels need strictly decreasing
5
Early Termination
Return false immediately if any constraint is violated
Key Takeaway
๐ฏ Key Insight: Use BFS to process levels sequentially, validating both parity (odd/even) and ordering (increasing/decreasing) constraints simultaneously in a single pass for optimal O(n) performance.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code