Find Minimum Swaps Required to Convert a Binary Tree into a BST
Problem and 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. |
How it works
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.
- Perform an inorder traversal of the binary tree to extract an array of node values. This array represents the tree's current order.
- Create an array of pairs where each pair contains the node's
valueand itsoriginal indexin the inorder array. - Sort this array of pairs based on the
valueto obtain the order that the BST would have. - Initialize a
visitedarray (or equivalent) to keep track of processed indices. - 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.
- 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.
Implementation and efficiency
C implementation
#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;
}C++ implementation
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void inorder(TreeNode* root, vector<int>& arr) {
if (!root) return;
inorder(root->left, arr);
arr.push_back(root->val);
inorder(root->right, arr);
}
int minSwaps(vector<int>& arr) {
int n = arr.size();
vector<pair<int, int>> arrPos(n);
for (int i = 0; i < n; i++) arrPos[i] = {arr[i], i};
sort(arrPos.begin(), arrPos.end());
vector<bool> visited(n, false);
int swaps = 0;
for (int i = 0; i < n; i++) {
if (visited[i] || arrPos[i].second == i) continue;
int cycle_size = 0, j = i;
while (!visited[j]) {
visited[j] = true;
j = arrPos[j].second;
cycle_size++;
}
if (cycle_size > 0) swaps += (cycle_size - 1);
}
return swaps;
}
int minSwapsToBST(TreeNode* root) {
vector<int> inorderArr;
inorder(root, inorderArr);
return minSwaps(inorderArr);
}
int main() {
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(6);
root->right = new TreeNode(7);
root->left->left = new TreeNode(8);
root->left->right = new TreeNode(9);
cout << "Minimum swaps required: " << minSwapsToBST(root) << endl;
return 0;
}Python implementation
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder(root, arr):
if root:
inorder(root.left, arr)
arr.append(root.val)
inorder(root.right, arr)
def minSwaps(arr):
n = len(arr)
arrPos = list(enumerate(arr))
arrPos.sort(key=lambda x: x[1])
visited = [False] * n
swaps = 0
for i in range(n):
if visited[i] or arrPos[i][0] == i:
continue
cycle_size = 0
j = i
while not visited[j]:
visited[j] = True
j = arrPos[j][0]
cycle_size += 1
if cycle_size > 0:
swaps += (cycle_size - 1)
return swaps
def minSwapsToBST(root):
inorder_arr = []
inorder(root, inorder_arr)
return minSwaps(inorder_arr)
# Example usage
if __name__ == '__main__':
root = TreeNode(5, TreeNode(6, TreeNode(8), TreeNode(9)), TreeNode(7))
print("Minimum swaps required:", minSwapsToBST(root))Java implementation
import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
class Pair {
int index, val;
Pair(int index, int val) {
this.index = index;
this.val = val;
}
}
public class MinSwapsToBST {
static void inorder(TreeNode root, List<Integer> arr) {
if (root == null) return;
inorder(root.left, arr);
arr.add(root.val);
inorder(root.right, arr);
}
static int minSwaps(List<Integer> arr) {
int n = arr.size();
Pair[] pairs = new Pair[n];
for (int i = 0; i < n; i++) {
pairs[i] = new Pair(i, arr.get(i));
}
Arrays.sort(pairs, Comparator.comparingInt(p -> p.val));
boolean[] visited = new boolean[n];
int swaps = 0;
for (int i = 0; i < n; i++) {
if (visited[i] || pairs[i].index == i) continue;
int cycle_size = 0, j = i;
while (!visited[j]) {
visited[j] = true;
j = pairs[j].index;
cycle_size++;
}
if (cycle_size > 0) swaps += (cycle_size - 1);
}
return swaps;
}
static int minSwapsToBST(TreeNode root) {
List<Integer> inorderArr = new ArrayList<>();
inorder(root, inorderArr);
return minSwaps(inorderArr);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(5);
root.left = new TreeNode(6);
root.right = new TreeNode(7);
root.left.left = new TreeNode(8);
root.left.right = new TreeNode(9);
System.out.println("Minimum swaps required: " + minSwapsToBST(root));
}
}JavaScript implementation
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function inorder(root, arr) {
if (!root) return;
inorder(root.left, arr);
arr.push(root.val);
inorder(root.right, arr);
}
function minSwaps(arr) {
const n = arr.length;
const arrPos = arr.map((val, index) => ({ index, val }));
arrPos.sort((a, b) => a.val - b.val);
const visited = new Array(n).fill(false);
let swaps = 0;
for (let i = 0; i < n; i++) {
if (visited[i] || arrPos[i].index === i) continue;
let cycle_size = 0;
let j = i;
while (!visited[j]) {
visited[j] = true;
j = arrPos[j].index;
cycle_size++;
}
if (cycle_size > 0) swaps += (cycle_size - 1);
}
return swaps;
}
function minSwapsToBST(root) {
const inorderArr = [];
inorder(root, inorderArr);
return minSwaps(inorderArr);
}
// Example usage
const root = new TreeNode(5, new TreeNode(6, new TreeNode(8), new TreeNode(9)), new TreeNode(7));
console.log("Minimum swaps required:", minSwapsToBST(root));Go implementation
package main
import (
"fmt"
"sort"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func inorder(root *TreeNode, arr *[]int) {
if root == nil {
return
}
inorder(root.Left, arr)
*arr = append(*arr, root.Val)
inorder(root.Right, arr)
}
type Pair struct {
Index int
Val int
}
func minSwaps(arr []int) int {
n := len(arr)
arrPos := make([]Pair, n)
for i := 0; i < n; i++ {
arrPos[i] = Pair{i, arr[i]}
}
sort.Slice(arrPos, func(i, j int) bool {
return arrPos[i].Val < arrPos[j].Val
})
visited := make([]bool, n)
swaps := 0
for i := 0; i < n; i++ {
if visited[i] || arrPos[i].Index == i {
continue
}
cycleSize := 0
j := i
for !visited[j] {
visited[j] = true
j = arrPos[j].Index
cycleSize++
}
if cycleSize > 0 {
swaps += (cycleSize - 1)
}
}
return swaps
}
func minSwapsToBST(root *TreeNode) int {
var inorderArr []int
inorder(root, &inorderArr)
return minSwaps(inorderArr)
}
func main() {
root := &TreeNode{5, &TreeNode{6, &TreeNode{8, nil, nil}, &TreeNode{9, nil, nil}}, &TreeNode{7, nil, nil}}
fmt.Println("Minimum swaps required:", minSwapsToBST(root))
}Rust implementation
use std::collections::HashMap;
#[derive(Debug)]
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
}
fn inorder(node: &Option<Box<TreeNode>>, result: &mut Vec<i32>) {
if let Some(ref n) = node {
inorder(&n.left, result);
result.push(n.val);
inorder(&n.right, result);
}
}
fn min_swaps(arr: &Vec<i32>) -> i32 {
let n = arr.len();
let mut arr_pos: Vec<(usize, i32)> = arr.iter().cloned().enumerate().collect();
arr_pos.sort_by_key(|&(_, val)| val);
let mut visited = vec![false; n];
let mut swaps = 0;
for i in 0..n {
if visited[i] || arr_pos[i].0 == i {
continue;
}
let mut cycle_size = 0;
let mut j = i;
while !visited[j] {
visited[j] = true;
j = arr_pos[j].0;
cycle_size += 1;
}
if cycle_size > 0 {
swaps += cycle_size - 1;
}
}
swaps as i32
}
fn min_swaps_to_bst(root: &Option<Box<TreeNode>>) -> i32 {
let mut arr = Vec::new();
inorder(root, &mut arr);
min_swaps(&arr)
}
fn main() {
let root = Some(Box::new(TreeNode {
val: 5,
left: Some(Box::new(TreeNode {
val: 6,
left: Some(Box::new(TreeNode { val: 8, left: None, right: None })),
right: Some(Box::new(TreeNode { val: 9, left: None, right: None })),
})),
right: Some(Box::new(TreeNode { val: 7, left: None, right: None })),
}));
println!("Minimum swaps required: {}", min_swaps_to_bst(&root));
}Kotlin implementation
class TreeNode(val value: Int, var left: TreeNode? = null, var right: TreeNode? = null)
fun inorder(node: TreeNode?, result: MutableList<Int>) {
if (node == null) return
inorder(node.left, result)
result.add(node.value)
inorder(node.right, result)
}
fun minSwaps(arr: List<Int>): Int {
val n = arr.size
val arrPos = arr.mapIndexed { index, value -> index to value }.sortedBy { it.second }
val visited = BooleanArray(n)
var swaps = 0
for (i in 0 until n) {
if (visited[i] || arrPos[i].first == i) continue
var cycleSize = 0
var j = i
while (!visited[j]) {
visited[j] = true
j = arrPos[j].first
cycleSize++
}
if (cycleSize > 0) swaps += (cycleSize - 1)
}
return swaps
}
fun minSwapsToBST(root: TreeNode?): Int {
val inorderList = mutableListOf<Int>()
inorder(root, inorderList)
return minSwaps(inorderList)
}
fun main() {
val root = TreeNode(5,
TreeNode(6,
TreeNode(8),
TreeNode(9)),
TreeNode(7))
println("Minimum swaps required: ${minSwapsToBST(root)}")
}Swift implementation
class TreeNode {
var val: Int
var left: TreeNode?
var right: TreeNode?
init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
func inorder(_ node: TreeNode?, _ result: inout [Int]) {
guard let node = node else { return }
inorder(node.left, &result)
result.append(node.val)
inorder(node.right, &result)
}
func minSwaps(_ arr: [Int]) -> Int {
let n = arr.count
var arrPos = arr.enumerated().map { ($0.offset, $0.element) }
arrPos.sort { $0.1 < $1.1 }
var visited = Array(repeating: false, count: n)
var swaps = 0
for i in 0..<n {
if visited[i] || arrPos[i].0 == i { continue }
var cycle_size = 0
var j = i
while !visited[j] {
visited[j] = true
j = arrPos[j].0
cycle_size += 1
}
if cycle_size > 0 {
swaps += (cycle_size - 1)
}
}
return swaps
}
func minSwapsToBST(_ root: TreeNode?) -> Int {
var inorderArr = [Int]()
inorder(root, &inorderArr)
return minSwaps(inorderArr)
}
let root = TreeNode(5)
root.left = TreeNode(6)
root.right = TreeNode(7)
root.left?.left = TreeNode(8)
root.left?.right = TreeNode(9)
print("Minimum swaps required: \(minSwapsToBST(root))")TypeScript implementation
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val: number, left: TreeNode | null = null, right: TreeNode | null = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function inorder(root: TreeNode | null, arr: number[]): void {
if (!root) return;
inorder(root.left, arr);
arr.push(root.val);
inorder(root.right, arr);
}
function minSwaps(arr: number[]): number {
const n = arr.length;
const arrPos = arr.map((val, index) => ({ index, val })).sort((a, b) => a.val - b.val);
const visited = new Array(n).fill(false);
let swaps = 0;
for (let i = 0; i < n; i++) {
if (visited[i] || arrPos[i].index === i) continue;
let cycle_size = 0;
let j = i;
while (!visited[j]) {
visited[j] = true;
j = arrPos[j].index;
cycle_size++;
}
if (cycle_size > 0) swaps += (cycle_size - 1);
}
return swaps;
}
function minSwapsToBST(root: TreeNode | null): number {
const inorderArr: number[] = [];
inorder(root, inorderArr);
return minSwaps(inorderArr);
}
const root = new TreeNode(5, new TreeNode(6, new TreeNode(8), new TreeNode(9)), new TreeNode(7));
console.log("Minimum swaps required:", minSwapsToBST(root));