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

Problem

You are given the root of a binary tree with unique values. In one operation, you can choose any two nodes at the same level and swap their values. Return the minimum number of operations needed to make the values at each level sorted in a strictly increasing order. The level of a node is the number of edges along the path between it and the root node.

Examples

Example 1
Example 2
Example 3

Constraints

  • The number of nodes in the tree is in the range [1, 10^5]
  • 1 <= Node.val <= 10^5
  • All the values of the tree are unique

Solution

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

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026