Skip to content
Rain Hu's Workspace
Go back

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

Rain Hu

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


一、題目

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:
image1

Example 2: image2

Example 3: image3

Constraints:


二、分析

三、解題

1. DFS

int minimumOperations(TreeNode* root) {
    vector<vector<int>> vec; 
    dfs(root, vec, 0);
    int res = 0;
    for (auto v : vec) {
        res += minSwaps(v);
    }
    return res;
}
void dfs(TreeNode* root, vector<vector<int>>& vec, int depth) {
    if (!root) return;
    if (depth == vec.size()) {
        vec.push_back({});
    }
    vec[depth].push_back(root->val);
    dfs(root->left, vec, depth+1);
    dfs(root->right, vec, depth+1);
}

int minSwaps(vector<int>& arr){
    int n = arr.size();
    map<int,int> map;
    for (int i = 0; i < n; i++) {
        map[arr[i]] = i;
    }
    vector<bool> vis(n, false);
    sort(arr.begin(), arr.end());
    int ans = 0;
    for (int i = 0; i < n; i++) {
        if (vis[i] || map[arr[i]] == i) continue;
        int j = i, cycle = 0;
        while (!vis[j]) {
            vis[j] = true;
            j = map[arr[j]];
            cycle++;
        }
        if (cycle > 0) {
            ans += (cycle-1);
        }
    }
    return ans;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2472. Maximum Number of Non-overlapping Palindrome Substrings
Next
[LeetCode] 2470. Number of Subarrays With LCM Equal to K