Even Odd Tree (LeetCode 1609): Solution and Explanation

Medium
Tree
Breadth First Search
Binary Tree

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

  1. Put the root in a queue and set level = 0.
  2. At the start of each level, set prev to minus infinity on even levels and plus infinity on odd levels.
  3. For each node on the level: return false if node.val % 2 == level % 2 (wrong parity).
  4. On an even level return false if node.val <= prev; on an odd level return false if node.val >= prev.
  5. Set prev = node.val, queue the children, and after the level finishes increase level.
  6. 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]
  1. Level 0 is [1]: odd, and the only value, so it passes.
  2. Level 1 is [10, 4]: both even, and 10 > 4, so the row decreases. Pass.
  3. Level 2 is [3, 7, 9]: all odd and 3 < 7 < 9. Pass.
  4. Level 3 is [12, 8, 6, 2]: all even and strictly decreasing. Pass.
  5. 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 True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each node enters and leaves the queue once and is checked in constant time.

Space

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 prev at 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 prev must 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.