Python - BFS + HashMap O(nlogn) - Video Solution
You can refer to the video solution.\n\nSince sorting has to be done on row level, we will have to go through the tree level-wise using BFS.\nWe will have to st
You can refer to the [video solution](https://youtu.be/4XzEifpXNjU).\n\nSince sorting has to be done on row level, we will have to go through the tree level-wise using BFS.\nWe will have to store all the elements for the row in an array and then sort it to find each elements sorted position.\n\nWe will store this sorted position for each element using a HashMap.\n\nWe will go through each element in the row and try to swap it at the right position if it isn\'t already in its correct position.\nWe might have to swap multiple numbers together in a group.\n\n```\nclass Solution:\n    def minimumOperations(self, root: Optional[TreeNode]) -> int:\n        q = deque([root])\n        total = 0\n        \n        while q:\n            row = []\n            for _ in range(len(q)):\n                node = q.popleft()\n                row.append(node.val)\n                \n                if node.left:\n                    q.append(node.left)\n                    \n                if node.right:\n                    q.append(node.right)\n                    \n            pos = {n:i for i,n in enumerate(sorted(row))}\n            \n            visited = set()\n            \n            for i in range(len(row)):\n                index = i\n                cnt = 0\n                while index not in visited and pos[row[index]]!=index:\n                    visited.add(index)\n                    index = pos[row[index]]\n                    cnt+=1\n                total += max(0, cnt-1)\n                \n        return total
['Breadth-First Search', 'Python']