
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>
#define MAX_NODES 1000
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
void inorder(TreeNode* root, int* arr, int* index) {
if (root == NULL) return;
inorder(root->left, arr, index);
arr[(*index)++] = root->val;
inorder(root->right, arr, index);
}
TreeNode* buildBalancedBST(int* arr, int start, int end) {
if (start > end) return NULL;
int mid = (start + end) / 2;
TreeNode* node = createNode(arr[mid]);
node->left = buildBalancedBST(arr, start, mid - 1);
node->right = buildBalancedBST(arr, mid + 1, end);
return node;
}
TreeNode* balanceBST(TreeNode* root) {
int arr[MAX_NODES];
int index = 0;
inorder(root, arr, &index);
return buildBalancedBST(arr, 0, index - 1);
}
void printInorder(TreeNode* root) {
if (root == NULL) return;
printInorder(root->left);
printf("%d ", root->val);
printInorder(root->right);
}
int main() {
TreeNode* root = createNode(1);
root->right = createNode(2);
root->right->right = createNode(3);
root->right->right->right = createNode(4);
TreeNode* balanced = balanceBST(root);
printInorder(balanced);
printf("\n");
return 0;
}