Friday, October 9, 2015

node* BuildTree(int values[], int count, int start, int stop)
{
if (start > count) return NULL;
node* current = (node*) malloc(sizeof node);
memset((void*) current, 0, sizeof node);
current->value = values[start];
if (start >= stop) return current;
int left = start + 1;
int right = stop;
for (int k = start+1; k < stop; k++)
if (values[k] > current->value){
right = k;
break;
}
current->left = BuildTree(values, count, left, right-1);
current->right = BuildTree(values, count, right, stop);
return current;
}


int main(int argc, char* argv[])
{
int values[255] = {0};
int count = 0;

readElementsInOrder((int*)values,&count);
for (int i = 0; i < count; i++)
{
printf("%d", values[i]);
}
printf("\r\nOutput:\r\n");

node* root = NULL;
root = BuildTree(values, count, 0, count-1);
printPreOrder(root);

printf("\r\nwith both children\r\n");
node* victim = getNode(root, 7); // with both children
treeDelete(root, victim);
printPreOrder(root);
printf("\r\nwith left child\r\n");
victim = getNode(root, 8); // with left child
treeDelete(root, victim);
printPreOrder(root);
printf("\r\nwith no child\r\n");
victim = getNode(root, 2); // with no child
treeDelete(root, victim);
printPreOrder(root);
printf("\r\nwith right child\r\n");
victim = getNode(root, 4); // with right child
treeDelete(root, victim);
printPreOrder(root);
printf("finish");
}

No comments:

Post a Comment