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.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.
root=tree_node([6, 3, 8]) → 0
The levels are already in order: [6] and [3, 8].
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).
Node.val ≤ 10⁵root=tree_node([4, 9, 2, 1, 7, 8, 3])
3
Run checks the first 3 tests in your browser. Submit checks all 82 tests on the server, hidden ones included.