Even Odd Tree - Problem

A binary tree is named Even-Odd if it meets the following conditions:

  • The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
  • For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
  • For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).

Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.

Input & Output

Example 1 — Valid Even-Odd Tree
$ Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
Output: true
💡 Note: Level 0: [1] (odd, single node ✓), Level 1: [10,4] (even, 10>4 decreasing ✓), Level 2: [3,7,9] (odd, 3<7<9 increasing ✓), Level 3: [12,8,6,2] (even, 12>8>6>2 decreasing ✓)
Example 2 — Invalid Ordering
$ Input: root = [5,4,2,3,3,7]
Output: false
💡 Note: Level 0: [5] (odd ✓), Level 1: [4,2] (even, 4>2 decreasing ✓), Level 2: [3,3,7] (odd but 3=3 not strictly increasing ✗)
Example 3 — Invalid Parity
$ Input: root = [5,9,1,3,5,7]
Output: false
💡 Note: Level 0: [5] (odd ✓), Level 1: [9,1] (should be even but both are odd ✗)

Constraints

  • The number of nodes in the tree is in the range [1, 105]
  • 1 ≤ Node.val ≤ 106

Visualization

Tap to expand
Even-Odd Tree: Level-by-Level Validation1Level 0 (Even): Odd values ✓104Level 1 (Odd): Even, Decreasing ✓379Level 2 (Even): Odd, Increasing ✓Even Levels (0,2,4...)• Must have ODD values• Strictly INCREASINGOdd Levels (1,3,5...)• Must have EVEN values• Strictly DECREASINGValidation Result✓ Level 0: [1] odd✓ Level 1: [10,4] even, decreasing✓ Level 2: [3,7,9] odd, increasingResult: true
Understanding the Visualization
1
Input Tree
Binary tree with nodes at different levels
2
Level Rules
Even levels: odd values increasing, Odd levels: even values decreasing
3
Validation
Check each level against its constraints
Key Takeaway
🎯 Key Insight: Use BFS to validate level constraints immediately as you traverse each level
Asked in
Microsoft 15 Amazon 12 Facebook 8
32.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen