root of a binary tree. Levels are numbered from zero: the root is level 0, its children are level 1, and so on.
Call the tree alternating if:
- on every even-numbered level, all values are odd and strictly increase from left to right;
- on every odd-numbered level, all values are even and strictly decrease from left to right.
Return True if the tree is alternating, and False otherwise.root=tree_node([7, 8, 2, 1, 5, None, 9]) → True
Level 0: [7], odd. Level 1: [8, 2], even and decreasing. Level 2: [1, 5, 9], odd and increasing. Everything fits.
root=tree_node([3, 4, 6]) → False
Level 1 is even, but 4 then 6 goes up, while it must strictly go down.
root=tree_node([2]) → False
The root sits on level 0, which needs odd values.
root=tree_node([7, 8, 2, 1, 5, None, 9])
True
Run checks the first 3 tests in your browser. Submit checks all 136 tests on the server, hidden ones included.