Ctrl K

Sort Tree Levels by Swaps

Medium
You are given the root of a binary tree whose values are all distinct. In one operation you may pick two nodes on the same level (at the same distance from the root) and swap their values. Return the fewest operations needed so that on every level the values, read from left to right, are strictly increasing.
Example 1
root=tree_node([4, 9, 2, 1, 7, 8, 3]) → 3

On level 1 swap 9 and 2. Level 2 reads 1, 7, 8, 3: swap 7 and 3 to get 1, 3, 8, 7, then swap 8 and 7. Three swaps in total.

Example 2
root=tree_node([6, 3, 8]) → 0

The levels are already in order: [6] and [3, 8].

Example 3
root=tree_node([10, 20, 5, None, None, 40, 30]) → 2

One swap on level 1 (20 and 5) and one on level 2 (40 and 30).

Constraints
  • 1 ≤ number of nodes ≤ 10⁵
  • 1 ≤ Node.val ≤ 10⁵
  • All values are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Rows by Depth MediumSnake Through the Tree Levels MediumTree Levels From the Bottom Up MediumThe Tree Seen From the Right MediumTree Columns, Top Down Medium
loading Python…
Input
root=tree_node([4, 9, 2, 1, 7, 8, 3])
Expected
3

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