Build a huffman tree using min-heap - c

I came across some problems when building a huffman tree. When building the huffman tree, I use min-heap to implement. And I think the code of min-heap is work well, but when I run the building-huffman-Tree code, the error appears. I have dug into it for a long time, but I have no means to solve it.Hope someone help me sovle my problem.The code is following:
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
#define MaxData NULL
// Huffman tree的建树过程用最小堆时因为每次都可以挑出最小的两个元素组成
typedef struct TreeNode {
int weight;
struct TreeNode *left;
struct TreeNode *right;
}HuffmanTree;
typedef struct HeapStruct {
HuffmanTree *Elements[MaxSize+1]; // an array
int Size; // the number of item in array
int Capacity; /* the capacity of heap */
}MinHeap;
MinHeap *Create()
{ // create a empty heap
MinHeap *H;
H = (MinHeap *)malloc(sizeof(MinHeap));
H->Elements[0] = NULL;
H->Size = 0;
H->Capacity = MaxSize;
return H;
}
int isFull(MinHeap *H)
{ // judge the heap full or not
return (H->Size == MaxSize);
}
int isEmpty(MinHeap *H)
{ // judge the heap empty or not
return (H->Size == 0);
}
void Add(MinHeap *H, int item)
{ // add item to the array
if( isFull(H) )
{
printf("the heap is full.\n");
return;
}
HuffmanTree *T;
T = (HuffmanTree *)malloc(sizeof(HuffmanTree));
T->weight = item;
H->Elements[++(H->Size)] = T;
return;
}
void Insert(MinHeap *H, HuffmanTree *item)
{ // insert item
int i;
if( isFull(H) )
{
printf("the heap is full.\n");
return;
}
i = ++(H->Size);
for(; (H->Elements[i/2]->weight)>(item->weight);i/=2)
H->Elements[i] = H->Elements[i/2];
H->Elements[i] = item;
}
HuffmanTree *DeleteMin(MinHeap *H)
{ // delete item of the heap
int Parent, Child;
HuffmanTree *MinValueNode, *tempNode;
if( isEmpty(H) )
{
printf("the heap is empty.\n");
return NULL;
}
MinValueNode = H->Elements[1];
tempNode = H->Elements[H->Size--];
for(Parent=1; Parent*2<=H->Size; Parent=Child)
{
Child = Parent * 2;
if( (Child != H->Size) && (H->Elements[Child]->weight > H->Elements[Child+1]->weight) )
Child++;
if( tempNode->weight <= H->Elements[Child]->weight )
break;
else
H->Elements[Parent] = H->Elements[Child];
}
H->Elements[Parent] = tempNode;
return MinValueNode;
}
void PercDown(MinHeap *H, int i)
{ // adjustment of the heap
int Parent, Child;
HuffmanTree *temp;
temp = H->Elements[i];
for(Parent=i; Parent*2<=H->Size; Parent=Child)
{
Child = Parent * 2;
if( (Child != H->Size) && (H->Elements[Child]->weight > H->Elements[Child+1]->weight) )
Child++; // Child point to the min
if( temp->weight <= H->Elements[Child]->weight )
break;
else
H->Elements[Parent] = H->Elements[Child];
}
H->Elements[Parent] = temp;
}
void BuildMinHeap(MinHeap *H)
{
int i;
for(i=H->Size/2; i>0; i--)
PercDown(H, i);
return;
}
HuffmanTree *Huffman(MinHeap *H)
{ /* Assuming that H->Size weight hava existed in H->Elements[]->weight */
int i;
HuffmanTree *T;
BuildMinHeap( H ); // adjustment
for(i=1; i<H->Size; i++) // merge H->Size-1
{
T = (HuffmanTree *)malloc(sizeof(HuffmanTree));
T->left = DeleteMin( H );
T->right = DeleteMin( H );
T->weight = T->left->weight + T->right->weight;
Insert(H, T);
}
T = DeleteMin( H );
return T;
}
void print_heap(MinHeap *H)
{
if( isEmpty(H) )
{
printf("the heap is empty.\n");
return;
}
for(int i=1; i<=H->Size; i++)
printf("%d ", H->Elements[i]->weight);
printf("\n");
}
void print_tree(HuffmanTree *T)
{
if( T )
{
print_tree(T->left);
printf("%d ", T->weight);
print_tree(T->right);
}
return;
}
int main()
{
MinHeap *heap;
HuffmanTree *HT, *T;
heap = Create();
int x;
printf("please input data:\n");
scanf("%d", &x);
while( x )
{
Add(heap, x);
scanf("%d", &x);
}
printf("original items:\n");
print_heap( heap );
printf("the item number of heap%d\n", heap->Size);
BuildMinHeap(heap);
print_heap( heap );
HT = DeleteMin( heap );
printf("删除的结点的值为%d\n", HT->weight);
print_heap( heap );
HT = Huffman( heap );
print_tree( HT );
return 0;
}

Related

How to remove necessary nodes from a binary tree?

Good evening forum members.
The following is on the agenda:
Read a sequence of coordinates (x, y, z) of spatial points from the file, ordered by distance from the point of origin (develop a separate function for calculating the distance and store this value in the data structure);
To bypass use the bottom option from right to left;
Extract from the tree all nodes whose z coordinate falls within the specified range zmin ..zmax (I decided to take from 7 to 14) and indicate their number;
To completely erase the tree, use the direct (from the root) version of the bypass from left to right;
Print the entire tree using a non-recursive function.
Please help with number 3. It is not possible to implement the deletion algorithm according to a given condition. It either does not work at all, or errors arrive (
Thanks in advance to everyone who responds
CODE:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_LEN 8
#define STACK_INIT_SIZE 20
typedef struct Tree {
int z;
int viddal;
struct Tree* left, * right;
} TREE;
typedef struct Stack {
size_t size, limit;
TREE** data;
} STACK;
int Distance(FILE* ftxt, int* vid, int* z_cord);
int CreateTreeFromFile(void);
TREE* NewNode(FILE* f, int viddal, int z);
void AddNewNode(TREE* pnew);
void PrintTreeNIZ(TREE* proot);
void iterPostorder(TREE* root);
void OutputTreeStructure(const char* title);
void ShowTree(TREE* proot, int level);
void ShowLevels(void);
int TreeHeight(TREE* proot);
void EraseTree(TREE* proot);
void DeleteSomeNodes(void);
int DeleteNode(TREE* pnew_adr);
TREE* root;
int main(){
system("chcp 1251");
if (CreateTreeFromFile() == 0)
return 0;
puts("\n Created tree: ");
PrintTreeNIZ(root);
OutputTreeStructure("of created tree");
DeleteSomeNodes();
OutputTreeStructure("of the new tree");
EraseTree(root);
root = NULL;
puts("\n Tree was deleted from DM\n\n");
return 0;
}
int Distance(FILE* ftxt, int *vid, int* z_cord) {
TREE* pel = (TREE*)malloc(sizeof(TREE));
if (feof(ftxt)) {;
return NULL;
}
else {
int x, y, z;
fscanf(ftxt, "%d%d%d", &x, &y, &z);
*z_cord = z;
*vid = sqrt(x * x + y * y + z * z);
}
}
int CreateTreeFromFile()
{
const char* fname = "Cords_1.txt";
FILE* fvoc = fopen(fname, "r");
if (fvoc == NULL) {
printf("\n\t\tCan`t open file %s...\n", fname);
return 0;
}
TREE* node;
int viddal, z;
Distance(fvoc, &viddal, &z);
while ((node = NewNode(fvoc, viddal, z)) != NULL) {
AddNewNode(node);
Distance(fvoc, &viddal, &z);
}
fclose(fvoc);
return 1;
}
TREE* NewNode(FILE* f, int viddal, int z)
{
TREE* pel;
pel = (TREE*)malloc(sizeof(TREE));
if (feof(f)) {
return NULL;
}
pel->viddal = viddal;
pel->z = z;
pel->left = pel->right = NULL;
return pel;
}
void AddNewNode(TREE* pnew) {
if (root == NULL) {
root = pnew;
return;
}
TREE* prnt = root;
do {
if (pnew->viddal == prnt->viddal) {
free(pnew);
return;
}
if (pnew->viddal < prnt->viddal) {
if (prnt->left == NULL) {
prnt->left = pnew;
return;
}
else
prnt = prnt->left;
}
else {
if (prnt->right == NULL) {
prnt->right = pnew;
return;
}
else
prnt = prnt->right;
}
} while (1);
}
void PrintTreeNIZ(TREE* proot)
{
if (proot == NULL)
return;
printf("\n Right Tree");
iterPostorder(proot->right);
printf("\n\n Left Tree");
iterPostorder(proot->left);
printf("\n\n Korin - %d", proot->viddal);
}
void OutputTreeStructure(const char* title)
{
printf("\n\n\n Structur%s:\n\n", title);
ShowLevels();
ShowTree(root, 0);
puts("\n");
}
#define TAB 7
void ShowTree(TREE* proot, int level)
{
if (proot == NULL) return;
ShowTree(proot->right, level + 1);
printf("\n%*c%d", level * TAB + 10, ' ', proot->viddal);
ShowTree(proot->left, level + 1);
}
void ShowLevels(void)
{
int lev;
printf(" Level: ");
for (lev = 1; lev <= TreeHeight(root); lev++)
printf(" %-*d", 6, lev);
printf("\n\n");
}
int TreeHeight(TREE* proot)
{
int lh, rh;
if (proot == NULL) return 0;
lh = TreeHeight(proot->left);
rh = TreeHeight(proot->right);
return lh > rh ? lh + 1 : rh + 1;
}
void EraseTree(TREE* proot)
{
if (proot == NULL)
return;
EraseTree(proot->left);
EraseTree(proot->right);
free(proot);
}
STACK* createStack() {
Stack* tmp = (Stack*)malloc(sizeof(Stack));
tmp->limit = STACK_INIT_SIZE;
tmp->size = 0;
tmp->data = (TREE**)malloc(tmp->limit * sizeof(TREE*));
return tmp;
}
void freeStack(Stack** s) {
free((*s)->data);
free(*s);
*s = NULL;
}
void push(Stack* s, TREE* item) {
if (s->size >= s->limit) {
s->limit *= 2;
s->data = (TREE**)realloc(s->data, s->limit * sizeof(TREE*));
}
s->data[s->size++] = item;
}
TREE* pop(Stack* s) {
if (s->size == 0) {
exit(7);
}
s->size--;
return s->data[s->size];
}
TREE* peek(Stack* s) {
return s->data[s->size - 1];
}
void iterPostorder(TREE* root) {
Stack* ps = createStack();
TREE* lnp = NULL;
TREE* peekn = NULL;
while (!ps->size == 0 || root != NULL) {
if (root) {
push(ps, root);
root = root->left;
}
else {
peekn = peek(ps);
if (peekn->right && lnp != peekn->right) {
root = peekn->right;
}
else {
pop(ps);
printf("\n\t Visited -> %d", peekn->viddal);
lnp = peekn;
}
}
}
freeStack(&ps);
}
// HELP WITH THAT
//--------------------------------------------------------------------------------------------
void DeleteSomeNodes(void)
{
printf("\n\t Deleting needing nods:\n");
TREE* pfind = (TREE*)malloc(sizeof(TREE));
do {
if (pfind->z >= 7 && pfind->z <= 14) {
DeleteNode(root);
printf(" Number %d was deleted from tree\n", root);
}
} while (1);
puts("\n\n");
}
#define NoSubTree 0
#define LeftSubTree -1
#define RightSubTree 1
#define TwoSubTrees 2
int DeleteNode(TREE* pnew_adr)
{
TREE* proot = root;
int subtr;
if (proot == NULL) return 0;
if (pnew_adr->viddal < proot->viddal)
return DeleteNode(proot->left);
if (pnew_adr->viddal > proot->viddal)
return DeleteNode(proot->right);
if (proot->left == NULL && proot->right == NULL)
subtr = NoSubTree;
else if (proot->left == NULL)
subtr = RightSubTree;
else if (proot->right == NULL)
subtr = LeftSubTree;
else
subtr = TwoSubTrees;
switch (subtr) {
case NoSubTree:
root = NULL; break;
case LeftSubTree:
root = proot->left; break;
case RightSubTree:
root = proot->right; break;
case TwoSubTrees:
TREE* pnew_root = proot->right, * pnew_prnt = proot;
while (pnew_root->left != NULL) {
pnew_prnt = pnew_root;
pnew_root = pnew_root->left;
}
pnew_root->left = proot->left;
if (pnew_root != proot->right) {
pnew_prnt->left = pnew_root->right;
pnew_root->right = proot->right;
}
root = pnew_root;
}
free(proot);
return 1;
}
//--------------------------------------------------------------------------------------------

Why is my Hash Map insert function not working?

I am making a Hash Map with people's names as its key using C language. I am using separate chaining to resolve the collision.
This is my code:
#include<stdio.h>
#include<stdlib.h>
#define MinTableSize 1
#include <stdbool.h>
//Colission resolution Using linked list
struct ListNode;
typedef struct ListNode *Position;
struct HashTbl;
typedef struct HashTbl *HashTable;
typedef unsigned int Index;
Index Hash(const char *Key, int Tablesize)
{
unsigned int HashVal = 0;
while(*Key != '\0')
{
HashVal += *Key++;
}
return HashVal % Tablesize;
}
struct ListNode
{
int Element;
Position Next;
};
typedef Position List;
struct HashTbl
{
int TableSize;
List *TheLists;
};
//Function to find next prime number for the size
bool isPrime(int n)
{
if(n <= 1)
{
return false;
}
if(n <= 3)
{
return true;
}
if(n%2 == 0 || n%3 == 0)
{
return false;
}
for(int i = 5; i*i <= n; i = i + 6)
{
if(n%i == 0 || n%(i + 2) == 0)
{
return false;
}
}
return true;
}
int NextPrime(int N)
{
if(N <= 1)
{
return 2;
}
int prime = N;
bool found = false;
while(!found)
{
prime++;
if(isPrime(prime))
{
found = true;
}
}
return prime;
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
int i;
if(TableSize < MinTableSize)
{
printf("Table size is too small\n");
return NULL;
}
H = malloc(sizeof(struct HashTbl));
if(H == NULL)
{
printf("Out of space\n");
return NULL;
}
H->TableSize = NextPrime(TableSize);
H->TheLists = malloc(sizeof(List) * H->TableSize);
if(H->TheLists == NULL)
{
printf("Out of space\n");
return NULL;
}
for(i = 0; i < H->TableSize; i++)
{
H->TheLists[i] = malloc(sizeof(struct ListNode));
if(H->TheLists[i] == NULL)
{
printf("Out of space\n");
return NULL;
}
else
{
H->TheLists[i]->Next = NULL;
}
}
return H;
}
//funtion to find the value
Position Find(const char *Key, HashTable H)
{
Position P;
List L;
L = H->TheLists[Hash(Key, H->TableSize)];
P = L->Next;
while(P != NULL && P->Element != Key)
{
P = P->Next;
}
return P;
}
void Insert(const char *Key, HashTable H)
{
Position Pos;
Position NewCell;
List L;
Pos = Find(Key, H);
if(Pos == NULL)
{
NewCell = malloc(sizeof(struct ListNode));
if(NewCell == NULL)
{
printf("Out of space\n");
return NULL;
}
else
{
L = H->TheLists[Hash(Key, H->TableSize)];
NewCell->Next;
NewCell->Element = Key;
L->Next = NewCell;
printf("Key inserted\n");
}
}
else
{
printf("Key already exist\n");
}
}
int main()
{
char Name[6][20] = {"Joshua", "Erica", "Elizabeth", "Monica", "Jefferson", "Andrian"};
int Size = sizeof(Name[0])/sizeof(Name[0][0]);
HashTable H = InitializeTable(Size);
Insert(Name[0], H);
Insert(Name[1], H);
Insert(Name[2], H);
Insert(Name[3], H);
}
The putout of this code is:
Key inserted
Key inserted
This means, it only successfully inserted two keys, while the other name has not been inserted. I think there's some error in my Insert() function, but I got no clue. I tried using an online compiler and it compile properly.

Bucket Sort Algo

How can i change code here to work with float values in the array, when I'm trying to compile the code, I got an error
so what I need here is my code can work with float values not just int, If i added an array with int values it works fine but with float values it gives me an error
How can i change code here to work with float values in the array, when I'm trying to compile the code, I got an error
so what I need here is my code can work with float values not just int, If i added an array with int values it works fine but with float values it gives me an error
#include <stdio.h>
#include <stdlib.h>
#define NARRAY 100 // Array size
#define NBUCKET 100 // Number of buckets
#define INTERVAL 100 // Each bucket capacity
struct Node {
int data;
struct Node *next;
};
void BucketSort(int arr[]);
struct Node *InsertionSort(struct Node *list);
void print(int arr[]);
void printBuckets(struct Node *list);
int getBucketIndex(int value);
// Sorting function
void BucketSort(int arr[]) {
int i, j;
struct Node **buckets;
// Create buckets and allocate memory size
buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET);
// Initialize empty buckets
for (i = 0; i < NBUCKET; ++i) {
buckets[i] = NULL;
}
// Fill the buckets with respective elements
for (i = 0; i < NARRAY; ++i) {
struct Node *current;
int pos = getBucketIndex(arr[i]);
current = (struct Node *)malloc(sizeof(struct Node));
current->data = arr[i];
current->next = buckets[pos];
buckets[pos] = current;
}
// Print the buckets along with their elements
for (i = 0; i < NBUCKET; i++) {
printf("Bucket[%d]: ", i);
printBuckets(buckets[i]);
printf("\n");
}
// Sort the elements of each bucket
for (i = 0; i < NBUCKET; ++i) {
buckets[i] = InsertionSort(buckets[i]);
}
printf("-------------\n");
printf("Bucktets after sorting\n");
for (i = 0; i < NBUCKET; i++) {
printf("Bucket[%d]: ", i);
printBuckets(buckets[i]);
printf("\n");
}
// Put sorted elements on arr
for (j = 0, i = 0; i < NBUCKET; ++i) {
struct Node *node;
node = buckets[i];
while (node) {
arr[j++] = node->data;
node = node->next;
}
}
return;
}
// Function to sort the elements of each bucket
struct Node *InsertionSort(struct Node *list) {
struct Node *k, *nodeList;
if (list == 0 || list->next == 0) {
return list;
}
nodeList = list;
k = list->next;
nodeList->next = 0;
while (k != 0) {
struct Node *ptr;
if (nodeList->data > k->data) {
struct Node *tmp;
tmp = k;
k = k->next;
tmp->next = nodeList;
nodeList = tmp;
continue;
}
for (ptr = nodeList; ptr->next != 0; ptr = ptr->next) {
if (ptr->next->data > k->data)
break;
}
if (ptr->next != 0) {
struct Node *tmp;
tmp = k;
k = k->next;
tmp->next = ptr->next;
ptr->next = tmp;
continue;
} else {
ptr->next = k;
k = k->next;
ptr->next->next = 0;
continue;
}
}
return nodeList;
}
int getBucketIndex(int value) {
return value / INTERVAL;
}
void print(int ar[]) {
int i;
for (i = 0; i < NARRAY; ++i) {
printf("%d ", ar[i]);
}
printf("\n");
}
// Print buckets
void printBuckets(struct Node *list) {
struct Node *cur = list;
while (cur) {
printf("%d ", cur->data);
cur = cur->next;
}
}
// Driver code
int main(void) {
int array[NARRAY] = {0.50, 100.00, 99.97, 51.20, 53.90, 28.10, 25.50, 66.40, 65.70, 0.00};
printf("Initial array: ");
print(array);
printf("-------------\n");
BucketSort(array);
printf("-------------\n");
printf("Sorted array: ");
print(array);
return 0;
}
Use this code. I've made my own datatype iORf. Use typedef int iORf and typedef float iORf for int and float respectively. You have to switch manually for this.
#include <stdio.h>
#include <stdlib.h>
#define NARRAY 100 // Array size
#define NBUCKET 100 // Number of buckets
#define INTERVAL 100 // Each bucket capacity
typedef int iORf; //float or int, currently int
struct Node
{
iORf data;
struct Node *next;
};
void BucketSort(iORf arr[]);
struct Node *InsertionSort(struct Node *list);
void print(iORf arr[]);
void printBuckets(struct Node *list);
int getBucketIndex(iORf value);
// Sorting function
void BucketSort(iORf arr[])
{
int i, j;
struct Node **buckets;
// Create buckets and allocate memory size
buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET);
// Initialize empty buckets
for (i = 0; i < NBUCKET; ++i)
{
buckets[i] = NULL;
}
// Fill the buckets with respective elements
for (i = 0; i < NARRAY; ++i)
{
struct Node *current;
int pos = getBucketIndex(arr[i]);
current = (struct Node *)malloc(sizeof(struct Node));
current->data = arr[i];
current->next = buckets[pos];
buckets[pos] = current;
}
// Print the buckets along with their elements
for (i = 0; i < NBUCKET; i++)
{
printf("Bucket[%d]: ", i);
printBuckets(buckets[i]);
printf("\n");
}
// Sort the elements of each bucket
for (i = 0; i < NBUCKET; ++i)
{
buckets[i] = InsertionSort(buckets[i]);
}
printf("-------------\n");
printf("Bucktets after sorting\n");
for (i = 0; i < NBUCKET; i++)
{
printf("Bucket[%d]: ", i);
printBuckets(buckets[i]);
printf("\n");
}
// Put sorted elements on arr
for (j = 0, i = 0; i < NBUCKET; ++i)
{
struct Node *node;
node = buckets[i];
while (node)
{
arr[j++] = node->data;
node = node->next;
}
}
return;
}
// Function to sort the elements of each bucket
struct Node *InsertionSort(struct Node *list)
{
struct Node *k, *nodeList;
if (list == 0 || list->next == 0)
{
return list;
}
nodeList = list;
k = list->next;
nodeList->next = 0;
while (k != 0)
{
struct Node *ptr;
if (nodeList->data > k->data)
{
struct Node *tmp;
tmp = k;
k = k->next;
tmp->next = nodeList;
nodeList = tmp;
continue;
}
for (ptr = nodeList; ptr->next != 0; ptr = ptr->next)
{
if (ptr->next->data > k->data)
break;
}
if (ptr->next != 0)
{
struct Node *tmp;
tmp = k;
k = k->next;
tmp->next = ptr->next;
ptr->next = tmp;
continue;
}
else
{
ptr->next = k;
k = k->next;
ptr->next->next = 0;
continue;
}
}
return nodeList;
}
int getBucketIndex(iORf value)
{
return (int)value / INTERVAL;
}
void print(iORf ar[])
{
int i;
int flag = 0;
iORf dummy = 1.5;
if (dummy > 1)
flag++;
for (i = 0; i < NARRAY; ++i)
{
if (flag > 0)
printf("%f ", ar[i]);
else
printf("%d ", ar[i]);
}
printf("\n");
}
// Print buckets
void printBuckets(struct Node *list)
{
struct Node *cur = list;
while (cur)
{
printf("%d ", cur->data);
cur = cur->next;
}
}
// Driver code
int main(void)
{
iORf array[NARRAY] = {0.5, 100.00, 99.97, 51.20, 53.90, 28.10, 25.50, 66.40, 65.70, 0.00};
printf("Initial array: ");
print(array);
printf("-------------\n");
BucketSort(array);
printf("-------------\n");
printf("Sorted array: ");
print(array);
return 0;
}

XOR maximization using a trie

I am trying to solve this question-
Given an array A of unsigned 32-bit ints, choose two in-bounds indices i, j so as to maximize the value of A[i] ^ A[j], where ^ is the bitwise XOR (exclusive OR) operator.
Example Input:
4 2 0 13 49
Output:
60
Explanation: 13 ^ 49 is 60
Here is my code
#include <stdio.h>
void insert(int n, int pos, struct node *t);
int find(struct node *p1, struct node *p2);
struct node *alloc();
struct node{
int value;
struct node *left;
struct node *right;
};
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n;
scanf("%d", &n);
struct node root;
root.value = 0;
root.left = root.right = NULL;
while (n--)
{
int num;
scanf("%d", &num);
insert(num, 31 , &root);
}
int max = find(&root, &root);
printf("%d\n", max);
}
return 0;
}
void insert(int n, int pos, struct node *t)
{
if (pos >= 0)
{
struct node *m;
int bit = (1 << pos)&n;
if (bit)
{
if (t->right == NULL)
{
m=alloc();
m->value = 1;
m->left = NULL;
m->right = NULL;
t->right = m;
}
if (pos == 0)
{
m=alloc();
m->value = n;
m->left = NULL;
m->right = NULL;
t->left = m;
}
insert(n, pos - 1, t->right);
}
else
{
if (t->left == NULL)
{
m = alloc();
m->value = 0;
m->left = NULL;
m->right = NULL;
t->left = m;
}
if (pos == 0)
{
m=alloc();
m->value = n;
m->left = NULL;
m->right = NULL;
t->left = m;
}
insert(n, pos - 1, t->left);
}
}
}
int find(struct node *p1, struct node *p2)
{
if ((p1->left != NULL) ||(p1->right != NULL))
{
int n01 = 0;
int n10 = 0;
if (p1->left != NULL && p2->right != NULL)
{
n01 = find(p1->left, p2->right);
}
if ((p1->right != NULL) && (p2->left != NULL))
{
n10 = find(p2->left, p1->right);
}
else
{
if (p1->left!=NULL && p2->left!=NULL)
n01 = find(p1->left, p2->left);
else
n10 = find(p1->right, p2->right);
}
return (n01 > n10 ? n01 : n10);
}
else
{
return p1->value^p2->value;
}
}
struct node *alloc()
{
return (struct node *) malloc(sizeof(struct node));
}
I am only getting a 0 as output.I know there are mistakes in my code.Please help me in finding the mistakes or if necessary the right solution.

top-bottom binary tree display

The following code displays my created binary tree from left to right on the console window. How do I print it from the top to the bottom, as you would on paper?
// Binary Trees Implementation
#include<stdio.h>
#include<stdlib.h>
typedef struct BTNode
{
int key;
struct BTNode *left, *right;
};
void displayBT(BTNode *p, int level);
BTNode *buildBT();
void RSD(BTNode *p);
void SRD(BTNode *p);
void SDR(BTNode *p);
int main()
{
int op;
BTNode *root;
do
{
printf("\n 1. Build Binary Tree");
printf("\n 2. Display Binary Tree");
printf("\n 3. Display Traversals");
printf("\n 0. Exit");
printf("\n........................\n");
scanf("\n %d", &op);
switch(op)
{
case 1:
root=buildBT();
break;
case 2:
displayBT(root,0);
break;
case 3:
printf("\n Pre-Order:");
RSD(root);
printf("\n In-Order:");
SRD(root);
printf("\n Post-Order:");
SDR(root);
printf("\n.....................\n");
break;
}
} while(op);
}
BTNode *buildBT()
{
int value;
BTNode *p;
printf("\n k=");
scanf("%d",&value);
if(value!=0)
{
p=(BTNode *)malloc(sizeof(BTNode));
p->key = value;
p->left = buildBT();
p->right = buildBT();
} else p=NULL;
return p;
}
void displayBT(BTNode *p, int level)
{
if(p!=NULL)
{
displayBT(p->right, level+1);
for(int j=0; j<=level;j++)
printf(" ");
printf("%d \n", p->key);
displayBT(p->left, level+1);
}
}
void RSD(BTNode *p)
{
if(p!=NULL)
{
printf("%d ", p->key);
RSD(p->left);
RSD(p->right);
}
}
void SRD(BTNode *p)
{
if(p!=NULL)
{
SRD(p->left);
printf("%d ", p->key);
SRD(p->right);
}
}
void SDR(BTNode *p)
{
if(p!=NULL)
{
SDR(p->left);
SDR(p->right);
printf("%d ", p->key);
}
}
Ok so I uploaded the full code because I was having trouble with the suggestions and maybe I should have done this from the beginning.
gave it another go, actually tried it now. works for me
void print_box(FILE* out, int i)
{
static char buff[16] = {0};
sprintf(buff,"%d",i);
int n = strlen(buff);
static char buf2[16] = {0};
strcpy(buf2,"[ ]");
int nn = 2 - (n-1)/2 ;
for(i=0;i<n;++i)
buf2[nn+i] = buff[i];
fprintf(out,"%s",buf2);
}
void print_empty_box(FILE* out) { fprintf(out,"%s","[ - ]"); }
typedef struct NodeRowTag
{
struct NodeRowTag* nxt;
BTNode* node;
} NodeRow;
NodeRow* make_head()
{
NodeRow* nr;
nr = (NodeRow*) malloc(sizeof(NodeRow));
nr->node = 0;
nr->nxt = 0;
return nr;
}
void push_back( NodeRow* nr, BTNode* n )
{
while( nr->nxt )
{
nr = nr->nxt;
}
nr->nxt = (NodeRow*) malloc(sizeof(NodeRow));
nr->nxt->node = n;
nr->nxt->nxt = 0;
}
void del_all( NodeRow* nr )
{
if( nr->nxt )
del_all(nr->nxt);
free( nr );
}
NodeRow* print_and_next( FILE* out, NodeRow* nr, int rownum, int maxnum )
{
// init spacing
int spacing = 0;
int stride = 3;
for(int i=rownum; i<maxnum; ++i)
{
spacing += stride;
stride *= 2;
}
for(int i=0;i<spacing;++i)
fprintf(out, " " );
// inbetween spacing
spacing = 1;
stride = 6;
for(int i=rownum; i<maxnum; ++i)
{
spacing += stride;
stride *= 2;
}
//
NodeRow* nxt = make_head();
NodeRow* n = nr->nxt;
while(n)
{
BTNode* p = n->node;
if(p) {
print_box(out,p->key);
push_back(nxt,p->left);
push_back(nxt,p->right);
} else {
print_empty_box(out);
push_back(nxt,0);
push_back(nxt,0);
}
for(int i=0;i<spacing;++i)
fprintf(out, " " );
n=n->nxt;
}
fprintf(out, "\n" );
del_all(nr);
return nxt;
}
int max(int a,int b) { return (a>b)?a:b; }
int max_depth( BTNode* p )
{
if(!p) return 0;
return 1 + max( max_depth(p->left), max_depth(p->right) );
}
void PrittyPrint( FILE* out )
{
int n = max_depth(root);
NodeRow* nr = make_head();
push_back(nr,root);
for(int i=1; i<=n; ++i)
{
nr = print_and_next( out, nr, i, n );
}
del_all(nr);
}
By printing the value of the current node BEFORE recursing right/left!

Resources