Binary TreesBinary Trees36
  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Inorder Traversal of a Binary Tree using Recursion
  4. 4Inorder Traversal of a Binary Tree using Iteration
  5. 5Postorder Traversal of a Binary Tree Using Recursion
  6. 6Postorder Traversal of a Binary Tree using Iteration
  7. 7Level Order Traversal of a Binary Tree using Recursion
  8. 8Level Order Traversal of a Binary Tree using Iteration
  9. 9Reverse Level Order Traversal of a Binary Tree using Iteration
  10. 10Reverse Level Order Traversal of a Binary Tree using Recursion
  11. 11Find Height of a Binary Tree
  12. 12Find Diameter of a Binary Tree
  13. 13Find Mirror of a Binary Tree
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree
GraphsGraphs46
  1. 1Breadth-First Search in Graphs
  2. 2Depth-First Search in Graphs
  3. 3Number of Provinces in an Undirected Graph
  4. 4Connected Components in a Matrix
  5. 5Rotten Oranges Problem - BFS in Matrix
  6. 6Flood Fill Algorithm - Graph Based
  7. 7Detect Cycle in an Undirected Graph using DFS
  8. 8Detect Cycle in an Undirected Graph using BFS
  9. 9Distance of Nearest Cell Having 1 - Grid BFS
  10. 10Surrounded Regions in Matrix using Graph Traversal
  11. 11Number of Enclaves in Grid
  12. 12Word Ladder - Shortest Transformation using Graph
  13. 13Word Ladder II - All Shortest Transformation Sequences
  14. 14Number of Distinct Islands using DFS
  15. 15Check if a Graph is Bipartite using DFS
  16. 16Topological Sort Using DFS
  17. 17Topological Sort using Kahn's Algorithm
  18. 18Cycle Detection in Directed Graph using BFS
  19. 19Course Schedule - Task Ordering with Prerequisites
  20. 20Course Schedule 2 - Task Ordering Using Topological Sort
  21. 21Find Eventual Safe States in a Directed Graph
  22. 22Alien Dictionary Character Order
  23. 23Shortest Path in Undirected Graph with Unit Distance
  24. 24Shortest Path in DAG using Topological Sort
  25. 25Dijkstra's Algorithm Using Set - Shortest Path in Graph
  26. 26Dijkstra’s Algorithm Using Priority Queue
  27. 27Shortest Distance in a Binary Maze using BFS
  28. 28Path With Minimum Effort in Grid using Graphs
  29. 29Cheapest Flights Within K Stops - Graph Problem
  30. 30Number of Ways to Reach Destination in Shortest Time - Graph Problem
  31. 31Minimum Multiplications to Reach End - Graph BFS
  32. 32Bellman-Ford Algorithm for Shortest Paths
  33. 33Floyd Warshall Algorithm for All-Pairs Shortest Path
  34. 34Find the City With the Fewest Reachable Neighbours
  35. 35Minimum Spanning Tree in Graphs
  36. 36Prim's Algorithm for Minimum Spanning Tree
  37. 37Disjoint Set (Union-Find) with Union by Rank and Path Compression
  38. 38Kruskal's Algorithm - Minimum Spanning Tree
  39. 39Minimum Operations to Make Network Connected
  40. 40Most Stones Removed with Same Row or Column
  41. 41Accounts Merge Problem using Disjoint Set Union
  42. 42Number of Islands II - Online Queries using DSU
  43. 43Making a Large Island Using DSU
  44. 44Bridges in Graph using Tarjan's Algorithm
  45. 45Articulation Points in Graphs
  46. 46Strongly Connected Components using Kosaraju's Algorithm

Minimum Swaps to Convert a Binary Tree into a BST - Algorithm & Code Examples

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