Minimum Number of Operations to Sort a Binary Tree by Level — LeetCode 2471 Python Solution

MediumTreeBreadth-First SearchBinary Tree
Problem
#2471
Reading time
6 min

The 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.

Example

Input
root = [1,4,3,7,6,8,5,null,null,null,null,9,null,10]
Output
3
Explanation
- Swap 4 and 3. The 2nd level becomes [3,4].

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minimumOperations(self, root: Optional[TreeNode]) -> int:
        def swap(arr, i, j):
            arr[i], arr[j] = arr[j], arr[i]

        def f(t):
            n = len(t)
            m = {v: i for i, v in enumerate(sorted(t))}
            for i in range(n):
                t[i] = m[t[i]]
            ans = 0
            for i in range(n):
                while t[i] != i:
                    swap(t, i, t[i])
                    ans += 1
            return ans

        q = deque([root])
        ans = 0
        while q:
            t = []
            for _ in range(len(q)):
                node = q.popleft()
                t.append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            ans += f(t)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2471. Minimum Number of Operations to Sort a Binary Tree by Level is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2471. Minimum Number of Operations to Sort a Binary Tree by Level?
LeetCode 2471. Minimum Number of Operations to Sort a Binary Tree by Level is rated Medium on LeetCode.
What is the time complexity of LeetCode 2471. Minimum Number of Operations to Sort a Binary Tree by Level?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2471. Minimum Number of Operations to Sort a Binary Tree by Level?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 2471. Minimum Number of Operations to Sort a Binary Tree by Level cover?
LeetCode 2471. Minimum Number of Operations to Sort a Binary Tree by Level is tagged Tree, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview