Even Odd Tree

A binary tree is Even-Odd when its levels follow two rules. The root is on level 0, its children on level 1, and so on. On every even-indexed level, all values are odd and strictly increase from left to right. On every odd-indexed level, all values are even and strictly decrease from left to right. Given the root, return true if the tree is Even-Odd, otherwise false.

30:00

Even Odd Tree
medium
Free written solution
Topics
Companies

A binary tree is Even-Odd when its levels follow two rules. The root is on level 0, its children on level 1, and so on. On every even-indexed level, all values are odd and strictly increase from left to right. On every odd-indexed level, all values are even and strictly decrease from left to right. Given the root, return true if the tree is Even-Odd, otherwise false.

Example 1:
Input: {"root":[1,10,4,3,null,7,9,12,8,6,null,null,2]}
Output: true
Constraints:
  • The number of nodes in the tree is in the range [1,105][1, 10^5].

  • 1≤Node.val≤1061 \leq \text{Node.val} \leq 10^6

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,10,4,3,null,7,9,12,8,6,null,null,2]}

Scan the tree level by level. Even levels need odd values going up left to right; odd levels need even values going down.

even level: odd values, increasing

odd level: even values, decreasing

L0↗L1↘L2↗L3↘110437912862

starting at the root

Variables
VariableValue
level-
previnf
node-
DepthFunction Call
Stack empty
0/19