Ctrl K

Reverse the Odd Tiers of a Tree

Medium
You get the root root of a perfect binary tree: every internal node has exactly two children and all leaves sit at the same depth. The root has depth 0, its children depth 1, and so on. On every odd depth, reverse the node values: if that level reads a, b, c, d from left to right, it must become d, c, b, a. The shape of the tree stays the same. Return the root.
Example 1
root=tree_node([1, 6, 9]) → [1, 9, 6]

At depth 1 the values 6 and 9 swap places.

Example 2
root=tree_node([4, 2, 8, 10, 20, 30, 40]) → [4, 8, 2, 10, 20, 30, 40]

Depth 1 is reversed into 8, 2. Depth 2 is even and stays 10, 20, 30, 40.

Example 3
root=tree_node([7]) → [7]

There are no odd depths, so the tree is unchanged.

Constraints
  • The tree has 1 to 2¹⁴ nodes
  • 0 ≤ Node.val ≤ 10⁵
  • The tree is perfect
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Tree Seen From the Right MediumTree Columns, Top Down MediumFirst Value on the Lowest Row MediumLargest Value on Each Tree Level MediumInsert a Tree Level Medium
loading Python…
Input
root=tree_node([1, 6, 9])
Expected
[1, 9, 6]

Run checks the first 3 tests in your browser. Submit checks all 13 tests on the server, hidden ones included.