LeetCode-in-Java

2471. Minimum Number of Operations to Sort a Binary Tree by Level

Medium

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

Example 1:

Input: root = [1,4,3,7,6,8,5,null,null,null,null,9,null,10]

Output: 3

Explanation:

We used 3 operations so return 3. It can be proven that 3 is the minimum number of operations needed.

Example 2:

Input: root = [1,3,2,7,6,5,4]

Output: 3

Explanation:

We used 3 operations so return 3. It can be proven that 3 is the minimum number of operations needed.

Example 3:

Input: root = [1,2,3,4,5,6]

Output: 0

Explanation: Each level is already sorted in increasing order so return 0.

Constraints:

Solution

import com_github_leetcode.TreeNode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public int minimumOperations(TreeNode root) {
        ArrayDeque<TreeNode> q = new ArrayDeque<>();
        int count = 0;
        if ((root.left != null && root.right != null) && (root.left.val > root.right.val)) {
            count++;
        }
        if (root.left != null) {
            q.add(root.left);
        }
        if (root.right != null) {
            q.add(root.right);
        }
        while (!q.isEmpty()) {
            int size = q.size();
            List<Integer> al = new ArrayList<>();
            while (size-- > 0) {
                TreeNode node = q.poll();
                assert node != null;
                if (node.left != null) {
                    al.add(node.left.val);
                    q.add(node.left);
                }
                if (node.right != null) {
                    al.add(node.right.val);
                    q.add(node.right);
                }
            }
            count += helper(al);
        }
        return count;
    }

    private int helper(List<Integer> list) {
        int swaps = 0;
        int[] sorted = new int[list.size()];
        for (int i = 0; i < sorted.length; i++) {
            sorted[i] = list.get(i);
        }
        Arrays.sort(sorted);
        Map<Integer, Integer> ind = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            ind.put(list.get(i), i);
        }

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) != sorted[i]) {
                swaps++;
                ind.put(list.get(i), ind.get(sorted[i]));
                list.set(ind.get(sorted[i]), list.get(i));
            }
        }
        return swaps;
    }
}