Even-Odd Tree
You are given the root of a binary tree. Check these rules, where the root is on level 0:
- On an even level, every value is odd and the values strictly increase from left to right.
- On an odd level, every value is even and the values strictly decrease from left to right.
Return True if every level follows its rule, otherwise False. A tree with a single node passes if its value is odd.
Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.
Example 1
root [1,10,4,3,null,7,9,12,8,6,null,null,2]
returns true
Every level follows its rule, so the answer is True.
Example 2
root [5,4,2,3,3,7]
returns false
Level 2 is [3, 3, 7]: not strictly increasing, so False.
Constraints
1 <= number of nodes <= 1001 <= node.val <= 1000
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.