
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
// Tree node structure
typedef struct TreeNode {
int val;
struct TreeNode *left, *right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
void storeInorder(TreeNode* root, int arr[], int* idx) {
if (!root) return;
storeInorder(root->left, arr, idx);
arr[(*idx)++] = root->val;
storeInorder(root->right, arr, idx);
}
void arrayToBST(TreeNode* root, int arr[], int* idx) {
if (!root) return;
arrayToBST(root->left, arr, idx);
root->val = arr[(*idx)++];
arrayToBST(root->right, arr, idx);
}
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
TreeNode* binaryTreeToBST(TreeNode* root) {
int arr[100], count = 0;
storeInorder(root, arr, &count);
qsort(arr, count, sizeof(int), compare);
int idx = 0;
arrayToBST(root, arr, &idx);
return root;
}
void printInorder(TreeNode* root) {
if (!root) return;
printInorder(root->left);
printf("%d ", root->val);
printInorder(root->right);
}
int main() {
TreeNode* root = createNode(10);
root->left = createNode(30);
root->right = createNode(15);
root->left->left = createNode(20);
root->right->right = createNode(5);
binaryTreeToBST(root);
printInorder(root);
return 0;
}