Skip to main content
LeetCode 2415, Medium. Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 17 parametrized pytest cases, and a playground notebook:

Problem

Given the root of a <strong>perfect</strong> binary tree, reverse the node values at each <strong>odd</strong> level of the tree. For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2]. Return <em>the root of the reversed tree</em>. A binary tree is <strong>perfect</strong> if all parent nodes have two children and all leaves are on the same level. The <strong>level</strong> of a node is the number of edges along the path between it and the root node.

Examples

Example 1
Example 2

Constraints

  • The number of nodes in the tree is in the range [1, 2^14]
  • 0 <= Node.val <= 10^5
  • root is a perfect binary tree

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026