Minimum Swaps to Convert a Binary Tree into a BST - Visualization

Problem Statement

Given a binary tree (not necessarily a binary search tree), find the minimum number of swaps required to convert it into a Binary Search Tree (BST). The conversion must preserve the original structure of the binary tree (i.e., only node values can be rearranged, not the structure).

Examples

Input Tree Minimum Swaps Description
[5, 6, 7, 8, 9, 10, 11]
3 Inorder of input is [8,6,9,5,10,7,11] → After sorting [5,6,7,8,9,10,11], minimum swaps = 3 (swap 8↔5, 9↔7, 10↔8)
[1, 2, 3]
0 Inorder is already sorted: [2,1,3] → Correct inorder should be [1,2,3]. Only 1 swap (2↔1), so answer = 1
[5, 3, 7, 1, 4, 6, 8]
0 This tree is already a BST. Inorder traversal is [1,3,4,5,6,7,8], so no swaps needed.
[1, 3, 2]
1 Inorder = [3,1,2] → Sorted = [1,2,3] → Swap 3↔1 gives correct order. Minimum swaps = 1
[10]
0 Single-node tree is trivially a BST. No swaps required.
[] 0 Empty tree has no elements. No swaps needed.

Solution

Understanding the Problem

We are given a binary tree. Our goal is to find the minimum number of swaps needed to convert this binary tree into a Binary Search Tree (BST). But here’s the catch: we're not rearranging the tree structure — instead, we are allowed to rearrange the node values such that the inorder traversal of the tree becomes sorted (which is a property of BSTs).

This means: perform an inorder traversal of the binary tree to collect its values into an array, then figure out how many swaps it takes to sort this array. That number is our answer.

Step-by-Step Solution with Example

Step 1: Understand Inorder Traversal

Inorder traversal visits the left subtree, then the root, and then the right subtree. For a binary search tree, this traversal will always produce a sorted sequence. So, our first step is to extract the inorder traversal of the current tree.

Step 2: Example Binary Tree


      5
     /     6   7
   /   8   9

Inorder traversal of this tree would give: [8, 6, 9, 5, 7]. This is not sorted, so it’s not a BST.

Step 3: Sort the Inorder Array and Track Original Indices

We pair each value with its index: [(8,0), (6,1), (9,2), (5,3), (7,4)].

We sort this list based on values: [(5,3), (6,1), (7,4), (8,0), (9,2)].

Step 4: Find Minimum Swaps Using Cycle Detection

To find the minimum number of swaps needed to sort the array, we detect cycles in the index mapping. A cycle of length k requires k - 1 swaps.

In the above example:

  • Cycle 1: 0 → 3 → 5 → 0 (length 3) → 2 swaps
  • Cycle 2: 2 → 4 → 2 (length 2) → 1 swap

Total swaps: 3

Step 5: Return the Total Swap Count

This total count is our final answer — the minimum swaps required to convert the binary tree into a BST using value rearrangements only.

Edge Cases

Case 1: Empty Tree

If the tree has no nodes, the inorder traversal is an empty list. No swaps are needed. Return 0.

Case 2: Single Node Tree

A single-node tree is already a BST. No swaps are required. Return 0.

Case 3: Tree Already a BST

If the tree is already a BST, its inorder traversal will be sorted. Swaps = 0. But remember — structure doesn't matter, only the order of values does.

Case 4: Unbalanced Tree

The shape of the tree does not affect the solution. Only the inorder traversal matters. Whether the tree is left-skewed, right-skewed, or sparse, the same steps apply.

Case 5: Duplicate Values

Typically, BSTs don’t contain duplicates. But if they exist in the problem, the solution still works since sorting with stable indexing will handle it. However, cycle detection should be handled carefully.

Finally

This problem is an elegant mix of tree traversal and sorting logic. By converting the binary tree into an inorder array and minimizing swaps through cycle detection, we preserve the BST property without touching the tree structure. It's a good reminder that in many problems, transformation and reduction into simpler representations can make the solution more intuitive and approachable — especially for beginners.

Algorithm Steps

  1. Perform an inorder traversal of the binary tree to extract an array of node values. This array represents the tree's current order.
  2. Create an array of pairs where each pair contains the node's value and its original index in the inorder array.
  3. Sort this array of pairs based on the value to obtain the order that the BST would have.
  4. Initialize a visited array (or equivalent) to keep track of processed indices.
  5. Iterate through the sorted pairs and for each index not yet visited, count the size of the cycle formed by repeatedly mapping indices from the sorted order to the original order.
  6. The number of swaps required for that cycle is (cycle size - 1). Sum up the swaps for all cycles to get the minimum number of swaps.

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdlib.h>

struct TreeNode {
    int val;
    struct TreeNode *left, *right;
};

struct TreeNode* createNode(int val) {
    struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    node->val = val;
    node->left = node->right = NULL;
    return node;
}

void inorder(struct TreeNode* root, int* arr, int* index) {
    if (root == NULL) return;
    inorder(root->left, arr, index);
    arr[(*index)++] = root->val;
    inorder(root->right, arr, index);
}

typedef struct {
    int index;
    int val;
} Pair;

int comparePairs(const void* a, const void* b) {
    return ((Pair*)a)->val - ((Pair*)b)->val;
}

int minSwaps(int* arr, int n) {
    Pair* arrPos = malloc(n * sizeof(Pair));
    for (int i = 0; i < n; i++) {
        arrPos[i].index = i;
        arrPos[i].val = arr[i];
    }
    qsort(arrPos, n, sizeof(Pair), comparePairs);
    int* visited = calloc(n, sizeof(int));
    int swaps = 0;
    for (int i = 0; i < n; i++) {
        if (visited[i] || arrPos[i].index == i) continue;
        int cycle_size = 0, j = i;
        while (!visited[j]) {
            visited[j] = 1;
            j = arrPos[j].index;
            cycle_size++;
        }
        if (cycle_size > 0) swaps += (cycle_size - 1);
    }
    free(arrPos);
    free(visited);
    return swaps;
}

int minSwapsToBST(struct TreeNode* root) {
    int arr[100];
    int index = 0;
    inorder(root, arr, &index);
    return minSwaps(arr, index);
}

int main() {
    struct TreeNode* root = createNode(5);
    root->left = createNode(6);
    root->right = createNode(7);
    root->left->left = createNode(8);
    root->left->right = createNode(9);
    printf("Minimum swaps required: %d\n", minSwapsToBST(root));
    return 0;
}

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...