/* * createTree * Function: Uses a CharCounts list to create a min-heap Huffman binary tree * Parameters: The CharCounts list to use * Return: The min-heap Huffman binary tree */ EncodingTree * createTree(CharCounts * counts) { EncodingTree * root; TreeQueue * queue; TreeQueue * toAdd; EncodingTree * temp1; EncodingTree * temp2; int nodeCount; CharCounts * tempCount; root = NULL; queue = NULL; toAdd = NULL; temp1 = NULL; temp2 = NULL; nodeCount = 0; tempCount = NULL; /* Insert all CharCounts into the TreeQueue (sorted least to greatest) */ tempCount = counts; while(tempCount != NULL) { toAdd = createBranch(tempCount); tempCount = tempCount->next; queue = insertInQueue(queue, toAdd); } /*printQueue(queue);*/ toAdd = NULL; /* * Remove from the TreeQueue, TWO AT A TIME, to create a singular binary tree, * and insert back into sorted queue accordingly * Continue until there is nothing left in the queue */ while(isEmpty(queue) == 0) { /*printf("boom\n");*/ if(toAdd != NULL) { queue = insertInQueue(queue, toAdd); } /* Remove two from queue */ temp1 = queue->root; /*printf("%c%d\n\nQueue1\n", temp1->letter, temp1->count);*/ /*printQueue(queue);*/ queue = queue->next; /*printf("Queue2\n");*/ /*printQueue(queue);*/ temp2 = queue->root; /*printf("%c%d\n\n", temp2->letter, temp2->count);*/ queue = queue->next; /*printQueue(queue);*/ temp2 = insertInTree(temp2, temp1); toAdd = createBranchFromTree(temp2); } root = toAdd->root; return(root); }
void insertInTree(node* root,int elem) { if(root->ele == elem) return; if(root->ele < elem) { if(root->right==NULL) root->right = createNode(elem); else insertInTree(root->right,elem); } else { if(root->left==NULL) root->left = createNode(elem); else insertInTree(root->left,elem); } return; }
int main() { int n; scanf("%d",&n); node* root = NULL; int elem,i; for(i=0; i<n; i++) { scanf("%d",&elem); if(root == NULL) root = createNode(elem); else insertInTree(root, elem); } printf("Printing Tree:\n"); printTree(root); printf("\n"); printf("After Reversal called:\n"); sumTree(root); printTree(root); return 0; }