Even Odd Tree (LeetCode 1609): Solution and Explanation
A binary tree is Even-Odd when every even-indexed level holds odd values in strictly increasing order and every odd-indexed level holds even values in strictly decreasing order. Return whether the given tree is Even-Odd.
Intuition
Both rules talk about one level at a time, read from left to right. Breadth-first search visits nodes in exactly that order, so each rule becomes a check between a node and the node just before it in the queue.
The parity rule needs only the node and the level index. The order rule needs only the previous value on the same level, so one variable that resets at the start of each level is enough.
Approach: Level-order BFS with a running previous value
- Put the root in a queue and set
level = 0. - At the start of each level, set
prevto minus infinity on even levels and plus infinity on odd levels. - For each node on the level: return false if
node.val % 2 == level % 2(wrong parity). - On an even level return false if
node.val <= prev; on an odd level return false ifnode.val >= prev. - Set
prev = node.val, queue the children, and after the level finishes increaselevel. - If the queue empties without a violation, return true.
Step-by-step example
root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
- Level 0 is [1]: odd, and the only value, so it passes.
- Level 1 is [10, 4]: both even, and 10 > 4, so the row decreases. Pass.
- Level 2 is [3, 7, 9]: all odd and 3 < 7 < 9. Pass.
- Level 3 is [12, 8, 6, 2]: all even and strictly decreasing. Pass.
- The queue is empty, so return true.
Code: Python, Java, C++
1class Solution:
2 def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:
3 queue = collections.deque([root])
4 level = 0
5 while queue:
6 prev = float('-inf') if level % 2 == 0 else float('inf')
7 for _ in range(len(queue)):
8 node = queue.popleft()
9 if node.val % 2 == level % 2:
10 return False
11 if level % 2 == 0 and node.val <= prev:
12 return False
13 if level % 2 == 1 and node.val >= prev:
14 return False
15 prev = node.val
16 if node.left:
17 queue.append(node.left)
18 if node.right:
19 queue.append(node.right)
20 level += 1
21 return True1class Solution {
2 public boolean isEvenOddTree(TreeNode root) {
3 Queue<TreeNode> queue = new LinkedList<>();
4 queue.offer(root);
5 int level = 0;
6 while (!queue.isEmpty()) {
7 int prev = level % 2 == 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
8 for (int size = queue.size(); size > 0; size--) {
9 TreeNode node = queue.poll();
10 if (node.val % 2 == level % 2) return false;
11 if (level % 2 == 0 && node.val <= prev) return false;
12 if (level % 2 == 1 && node.val >= prev) return false;
13 prev = node.val;
14 if (node.left != null) queue.offer(node.left);
15 if (node.right != null) queue.offer(node.right);
16 }
17 level++;
18 }
19 return true;
20 }
21}1class Solution {
2public:
3 bool isEvenOddTree(TreeNode* root) {
4 queue<TreeNode*> q;
5 q.push(root);
6 int level = 0;
7 while (!q.empty()) {
8 int prev = level % 2 == 0 ? INT_MIN : INT_MAX;
9 for (int size = q.size(); size > 0; size--) {
10 TreeNode* node = q.front();
11 q.pop();
12 if (node->val % 2 == level % 2) return false;
13 if (level % 2 == 0 && node->val <= prev) return false;
14 if (level % 2 == 1 && node->val >= prev) return false;
15 prev = node->val;
16 if (node->left) q.push(node->left);
17 if (node->right) q.push(node->right);
18 }
19 level++;
20 }
21 return true;
22 }
23};Time and space complexity
O(n)
Each node enters and leaves the queue once and is checked in constant time.
O(n)
The queue holds at most one full level, which can be about n / 2 nodes in a complete tree.
Other approaches
DFS with a last-value-per-level array (time O(n), space O(h))
Do a preorder DFS that visits left before right and keep last[depth], the most recent value seen on each depth. Since preorder reaches nodes of one depth from left to right, the same two checks work against last[depth].
Collect levels, then validate (time O(n), space O(n))
Build the full list of values per level first, then scan each list. Simpler to reason about but stores every value and cannot stop early.
Common mistakes
- Swapping the parity rule. Even levels hold odd values, and odd levels hold even values.
- Using non-strict comparisons. Two equal neighbours on a level break the rule.
- Forgetting to reset
prevat the start of each level, so the last value of one level is compared with the first value of the next. - Using a fixed sentinel like 0 for odd levels. Odd levels decrease, so their starting
prevmust be larger than any value.
Frequently asked questions
Why does [5,4,2,3,3,7] return false?
Level 2 is [3, 3, 7]. It must strictly increase, but the second 3 is not greater than the first.
Can I stop as soon as one node fails?
Yes. A single broken rule anywhere makes the tree not Even-Odd, so returning false immediately is correct and saves work.
Is a single node an Even-Odd tree?
Only if its value is odd, because it sits on level 0, which needs odd values. [1] returns true and [2] returns false.