Problem: Design a data structure which can perform most efficiently insert and median.
My Solution:
struct node
{
int number;
node *left;
node *right;
int leftTreeNode;
};
struct header
{
int totalNodes;
Int valid;
int median;
node *root;
} myhead ; //myhead ......thats where it will start.
void initialize() { valid = 0, median = 0, root =NULL, totalNodes =0; }
void AddNode ( int n )
{
myhead.totalNodes++;
myhead.valid = 0;
node *prev = NULL;
node *temp = myhead->root;
while ( temp != NULL )
{
if ( n <>number )
{
prev = temp;
temp->leftTreeNodes +=1;
temp = temp->left;
}
else
{
prev = temp;
temp = temp->right;
}
}
if ( prev != NULL )
{
if ( n <>number )
prev->left = createNode(n)
else
prev->right = createNode(n);
}
else
myhead->root = createNode(n);
}
int median ()
{
if (myhead.valid ) return median;
int mid = myhead.totalNodes/2;
node *prev = NULL;
node *temp = myhead.root;
while ( mid )
{
if ( mid > temp->leftTreeNodes )
{
mid = mid - (temp->leftTreeNodes)-1;//1 for root node
prev = temp;
temp = temp->right;
}
else
{
prev = temp;
temp = temp->left;
}
}
myhead.median = prev->number;
myhead.valid = 1;
return myhead.median;
}
My Solution:
struct node
{
int number;
node *left;
node *right;
int leftTreeNode;
};
struct header
{
int totalNodes;
Int valid;
int median;
node *root;
} myhead ; //myhead ......thats where it will start.
void initialize() { valid = 0, median = 0, root =NULL, totalNodes =0; }
void AddNode ( int n )
{
myhead.totalNodes++;
myhead.valid = 0;
node *prev = NULL;
node *temp = myhead->root;
while ( temp != NULL )
{
if ( n <>number )
{
prev = temp;
temp->leftTreeNodes +=1;
temp = temp->left;
}
else
{
prev = temp;
temp = temp->right;
}
}
if ( prev != NULL )
{
if ( n <>number )
prev->left = createNode(n)
else
prev->right = createNode(n);
}
else
myhead->root = createNode(n);
}
int median ()
{
if (myhead.valid ) return median;
int mid = myhead.totalNodes/2;
node *prev = NULL;
node *temp = myhead.root;
while ( mid )
{
if ( mid > temp->leftTreeNodes )
{
mid = mid - (temp->leftTreeNodes)-1;//1 for root node
prev = temp;
temp = temp->right;
}
else
{
prev = temp;
temp = temp->left;
}
}
myhead.median = prev->number;
myhead.valid = 1;
return myhead.median;
}
Comments
Post a Comment