Hello all!
I am trying to come up with the code to find the balanced BST with max height within a given BST. So far, I have some preliminaries:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Tree { int key;
struct Tree *left;
struct Tree *right;
} Tree;
Tree* InsertBST(Tree* t, int k)
{
if (t == NULL) {
Tree* w = (Tree*) malloc(sizeof(Tree));
w->key = k;
w->left = NULL;
w->right = NULL;
return w;
}
if (k <= t->key)
t->left = InsertBST(t->left, k);
else
t->right = InsertBST(t->right, k);
return t;
}
int max(int a, int b)
{
if (a >= b)
return a;
else
return b;
}
int height(Tree* t)
{
if (t == NULL)
return 0;
return 1 + max(height(t->left), height(t->right));
}
int IsBalanced(Tree *t)
{
int lheight;
int rheight;
if (t == NULL)
return 1;
lheight = height(t->left);
rheight = height(t->right);
if (abs(lheight-rheight) <= 1 &&
IsBalanced(t->left) &&
IsBalanced(t->right))
return 1;
return 0;
}
These work fine. The problem lies within the following function:
Code:
void MaxBalanced(Tree *t, Tree *maxBal, int *maxBal_height)
{
int t_height;
if (t == NULL)
*maxBal_height += 0;
if (IsBalanced(t) == 1){
t_height = height(t);
if (t_height >= *maxBal_height){
maxBal = t;
*maxBal_height = t_height;
}
}
else{
MaxBalanced(t->left, maxBal, maxBal_height);
MaxBalanced(t->right, maxBal, maxBal_height);
}
}
int main()
{
int i;
Tree* t = NULL;
int j[20] = { 993, 591, 2, 4, 395, 97, 446, 38, 279, 587, 28, 50, 265, 502, 114, 493, 808, 716, 897, 987 };
for (i = 0; i < 20; i++)
t = InsertBST(t, j[i]);
DisplayTree(t);
Tree* maxBal = NULL;
int maxBal_height = 0;
MaxBalanced(t, maxBal, &maxBal_height);
DisplayTree(maxBal);
return 0;
}
The code runs without errors but I get an empty tree. DisplayTree is a funtion which allows to present the tree graphically (too long to post here). I would appreciate any hints as to what is wrong with this approach.