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 Validation INPUT 1 L0 10 4 L1 3 7 9 L2 12 8 6 2 L3 Even Level (Odd) Odd Level (Even) root = [1,10,4,3,null,7,9, 12,8,6,null,null,2] BFS Level Order Traversal ALGORITHM STEPS 1 BFS with Level Track Use queue, track level index 2 Even Level Check Values: odd, strictly increasing 3 Odd Level Check Values: even, strictly decreasing 4 Validate All Levels Return true if all pass Level-by-Level Validation L0: [1] odd, increasing? OK L1: [10,4] even, dec? OK L2: [3,7,9] odd, inc? OK L3: [12,8,6,2] even,dec? OK All levels valid! FINAL RESULT true Valid Even-Odd Tree Validation Summary Level 0: OK (1 is odd) Level 1: OK (10 > 4) Level 2: OK (3 < 7 < 9) Level 3: OK (12>8>6>2) Output: true Tree satisfies all Even-Odd conditions Key Insight: BFS naturally processes nodes level by level. At each level, check: (1) Even levels must have ODD values in strictly increasing order. (2) Odd levels must have EVEN values in strictly decreasing order. Track previous value at each level to verify ordering. Time: O(n), Space: O(n) for the queue. TutorialsPoint - Even Odd Tree | BFS Approach
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