XOR maximization using a trie - c

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.

Related

Binary searching in tree

I need to create this tree:
the tree
I need to implement a function that takes the tree's node (root), a number, and returns how many times the binary representation of the number occurs in the tree.
For example:
9(1001) occurs 4 times
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct TreeNode {
int val;
struct TreeNode* leftNode;
struct TreeNode* rightNode;
};
void strrev(char * arr, int start, int end) {
char temp;
if (start >= end) {
return;
}
temp = * (arr + start);
*(arr + start) = * (arr + end);
*(arr + end) = temp;
start++;
end--;
strrev(arr, start, end);
}
char * itoa(int number, char * arr, int base) {
int i = 0, r, negative = 0;
if (number == 0) {
arr[i] = '0';
arr[i + 1] = '\0';
return arr;
}
if (number < 0 && base == 10) {
number *= -1;
negative = 1;
}
while (number != 0) {
r = number % base;
arr[i] = (r > 9) ? (r - 10) + 'a' : r + '0';
i++;
number /= base;
}
if (negative) {
arr[i] = '-';
i++;
}
strrev(arr, 0, i - 1);
arr[i] = '\0';
return arr;
}
int count_occurrences(struct TreeNode* root, int number) {
int count = 0;
char binary[33];
itoa(number, binary, 2);
int length = strlen(binary);
struct TreeNode* current = root;
for (int i = 0; i < length; i++) {
if (binary[i] == '0') {
if (current->leftNode != NULL) {
current = current->leftNode;
} else {
return count;
}
} else {
if (current->rightNode != NULL) {
current = current->rightNode;
} else {
return count;
}
}
if (current->val == number) {
count++;
}
}
return count;
}
struct TreeNode* createNode(int value) {
struct TreeNode* newNode = malloc(sizeof(struct TreeNode));
newNode->val = value;
newNode->leftNode = NULL;
newNode->rightNode = NULL;
return newNode;
}
struct TreeNode* insertLeftNode(struct TreeNode* rootNode, int value) {
rootNode->leftNode = createNode(value);
return rootNode->leftNode;
}
struct TreeNode* insertRightNode(struct TreeNode* rootNode, int value) {
rootNode->rightNode = createNode(value);
return rootNode->rightNode;
}
int main() {
struct TreeNode* rootNode = createNode(1);
insertLeftNode(rootNode, 1);
insertRightNode(rootNode, 0);
insertLeftNode(rootNode->leftNode, 0);
insertRightNode(rootNode->leftNode, 1);
insertLeftNode(rootNode->rightNode, 0);
insertRightNode(rootNode->rightNode, 0);
insertLeftNode(rootNode->leftNode->leftNode, 0);
insertRightNode(rootNode->leftNode->leftNode, 0);
insertLeftNode(rootNode->rightNode->rightNode, 0);
insertRightNode(rootNode->rightNode->rightNode, 0);
printf("\n%d", count_occurrences(rootNode, 9));
}
I am using itoa(), but for some reasons it doesn't return nothing.
Itoa gave compiler warning so i copied it from internet.
Also I think i am not correctly creating the tree.

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.

Getting Segmentation fault in C code while trying to assign a pointer to some object

I am trying to solve a question in C language. The problem statement is(reading whole problem is not important for my doubt):
Given an arbitrary unweighted rooted tree which consists of N nodes.
The goal of the problem is to find largest distance between two nodes in a tree.
Distance between two nodes is a number of edges on a path between the nodes (there will be a unique path between any pair of nodes since it is a tree).
The nodes will be numbered 0 through N - 1.
The tree is given as an array A, there is an edge between nodes A[i] and i (0 <= i < N). Exactly one of the i's will have A[i] equal to -1, it will be root node.
I made TreeNode and I am storing all next connections TreeNode pointers in array(like adjacency list in graph)
My solution is:
/**
* #input A : Integer array
* #input n1 : Integer array's ( A ) length
*
* #Output Integer
*/
struct TreeNode2 {
int value;
struct TreeNode2 *next;
};
struct TreeNode2* createNode(int n)
{
struct TreeNode2 *node = (struct TreeNode2 *)calloc(1, sizeof(struct TreeNode2));
node->value = n;
node->next = NULL;
return node;
}
int maximum(int a,int b)
{
if(a>b)
return a;
return b;
}
int dfs(struct TreeNode2 **tree, int node)
{
if( tree[node] == NULL )
return 0;
int len1 = 0;
int len2 = 0;
struct TreeNode2 *ptr = tree[node];
while(ptr!=NULL)
{
int curr = dfs(tree, (ptr->value));
if( curr > len1 )
{
len1 = curr;
}
else if(curr > len2)
{
len2 = curr;
}
ptr = ptr->next;
}
return maximum( len1 + len2 , maximum( len1 , len2 ) + 1 );
}
int solve(int* A, int n1)
{
struct TreeNode2 *tree[n1];
int i=0;
for(i=0;i<n1;i++)
{
tree[i] = NULL;
}
for(i=0;i<n1;i++)
{
if(A[i] != -1)
{
struct TreeNode2 *temp = tree[i];
struct TreeNode2 *newNode = createNode(A[i]);
tree[i] = newNode;
newNode->next = temp;
// printf("A[i] = %d \n",A[i]);
struct TreeNode2 *temp2 = tree[ A[i] ];
struct TreeNode2 *newNode2 = createNode(i);
tree[ A[i] ] = newNode2;
newNode2->next = temp2;
}
}
int ans = dfs(tree, 0);
return ans;
}
I'm getting the segmentation fault the moment I am adding
tree[ A[i] ] = newNode2;
in solve function in forloop for input -1, 0. I tried tree[A[i]] = NULL (it worked). The problem is when A[i] = 0, tree[0] = NULL is working but tree[0] = newNode2 is not working why.?
Finally I caught the problem, actually in this problem tree connection is undirected so the code is stuck in loop inside dfs. I used visited array to solve this issue.
From the link, the example explanation shows that node 0 has three [direct] children (nodes, 1, 2, 3).
I could be wrong about this, but I think an algorithm that works is as follows:
As we build the tree, we remember the node with the maximum depth.
After the tree is built, we can traverse it to find the maximum depth of any [leaf] node that is not max node we found when building.
The solution is the sum of the depth of those two nodes
Here's some code I wrote to do that. I submitted it for test input and it passed.
Edit: I've revised the test and now it passes all tests but exceeds the time limit in the "Efficiency" test.
I expected as much because of the [seeming] O(n^2) but I wanted to try a non-standard approach that doesn't use "visited".
I added some code to dump a text file that can be fed to graphviz with -DGRAPH. It produces an output file: grf. To process this, do:
dot -Tsvg < grf > grf.svg
Then, you can point your browser to the grf.svg file to display the graph.
Anyway, here's the working but slow code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define sysfault(_fmt...) \
do { \
printf(_fmt); \
exit(1); \
} while (0)
#ifndef ROOTLEAF
#define ROOTLEAF 0
#endif
#if ROOTLEAF
#define PTROK(_ptr) (_ptr != NULL)
#else
#define PTROK(_ptr) 1
#endif
#ifdef DEBUG
#define dbgprt(_fmt...) \
do { \
printf(_fmt); \
} while (0)
#define nodeshow(_node,_tag) \
do { \
_nodeshow(_node,_tag); \
} while (0)
#ifndef GRAPH
#define GRAPH
#endif
#else
#define dbgprt(_fmt...) \
do { \
} while (0)
#define nodeshow(_node,_tag) \
do { \
} while (0)
#endif
#define MAXNODE 40000
#define COUNTOF(_arr) \
(sizeof(_arr) / sizeof(_arr[0]))
typedef struct node node_t;
struct node {
int paridx;
int depth;
node_t *parent;
node_t *next;
node_t *cldhead;
node_t *cldtail;
node_t *leaf;
};
static node_t *root = NULL;
static node_t *lhsbest = NULL;
static node_t *rhsbest = NULL;
static int Acnt = -1;
static node_t nodelist[MAXNODE + 1] = { 0 };
static int soldepth;
static FILE *xfgrf;
static char *
tlsbuf(void)
{
static int bufidx = 0;
static char buf[16][1000];
char *bp;
bp = buf[bufidx];
++bufidx;
bufidx %= 16;
*bp = 0;
return bp;
}
static int
nodenum(node_t *node)
{
if (node != NULL)
return node - nodelist;
else
return -1;
}
static char *
nodexid(node_t *lhs,node_t *rhs)
{
int lhsnum = nodenum(lhs);
int rhsnum = nodenum(rhs);
int tmp;
char *buf;
if (lhsnum > rhsnum) {
tmp = lhsnum;
lhsnum = rhsnum;
rhsnum = tmp;
}
buf = tlsbuf();
sprintf(buf,"%d,%d",lhsnum,rhsnum);
return buf;
}
static void
_nodeshow(node_t *node,const char *tag)
{
#ifdef DEBUG
if (node != NULL) {
dbgprt("nodeshow: %s node=%d paridx=%d depth=%d\n",
tag,nodenum(node),node->paridx,node->depth);
}
else
dbgprt("nodeshow: %s null\n",tag);
#endif
}
// newnode -- create new node;
static node_t *
newnode(int idx,node_t *par)
{
node_t *node;
node = &nodelist[idx];
if (par != NULL) {
node->paridx = nodenum(par);
node->depth = par->depth + 1;
}
else
node->paridx = -1;
node->parent = par;
return node;
}
// fastfind -- find node based on i from A[i]
static node_t *
fastfind(int value)
{
node_t *node;
node = &nodelist[value];
nodeshow(node,"fastfind");
return node;
}
// addchild -- attach child node to parent
static void
addchild(node_t *par,node_t *cld)
{
cld->next = par->cldhead;
par->cldhead = cld;
}
int
pathok(node_t *cur)
{
int okay;
if (ROOTLEAF)
okay = (cur != NULL);
else
okay = (cur != NULL) && (cur != root);
return okay;
}
int
pathcost(node_t *lhs,node_t *rhs)
{
int lhsok;
int rhsok;
int cost;
dbgprt("pathcost: ENTER lhs=%d rhs=%d xid=%s\n",
nodenum(lhs),nodenum(rhs),nodexid(lhs,rhs));
cost = 0;
if (lhs == root) {
dbgprt("pathcost: QWKROOT\n");
cost = rhs->depth;
lhs = NULL;
rhs = NULL;
}
while (1) {
if ((lhs == NULL) && (rhs == NULL))
break;
// join at lower level than root
if (lhs == rhs)
break;
#ifdef DEBUG
nodeshow(lhs,"LHS");
nodeshow(rhs,"RHS");
#endif
lhsok = pathok(lhs);
rhsok = pathok(rhs);
if (PTROK(lhs) && PTROK(rhs) && (lhs->depth > rhs->depth)) {
//nodeshow(lhs,"LHSDEEP");
if (lhsok) {
cost += 1;
dbgprt("pathcost: LCOST/D cost=%d\n",cost);
lhs = lhs->parent;
}
continue;
}
if (PTROK(lhs) && PTROK(rhs) && (rhs->depth > lhs->depth)) {
//nodeshow(lhs,"RHSDEEP");
if (rhsok) {
cost += 1;
dbgprt("pathcost: RCOST/D cost=%d\n",cost);
rhs = rhs->parent;
}
continue;
}
if (PTROK(lhs) && lhsok) {
cost += 1;
dbgprt("pathcost: LCOST/S cost=%d\n",cost);
lhs = lhs->parent;
}
if (PTROK(rhs) && rhsok) {
cost += 1;
dbgprt("pathcost: RCOST/S cost=%d\n",cost);
rhs = rhs->parent;
}
}
dbgprt("pathcost: EXIT cost=%d\n",cost);
return cost;
}
void
search1(void)
{
int curcost;
node_t *end = &nodelist[Acnt];
node_t *leafbase = NULL;
node_t *lhs = NULL;
node_t *rhs = NULL;
int bestcost = 0;
int leafcnt = 0;
// link all leaf nodes together
for (rhs = nodelist; rhs < end; ++rhs) {
if (ROOTLEAF) {
if (rhs != nodelist) {
if (rhs->cldhead != NULL)
continue;
}
}
else {
if (rhs->cldhead != NULL)
continue;
}
nodeshow(rhs,"ISLEAF");
if (leafbase == NULL)
leafbase = rhs;
if (lhs != NULL)
lhs->leaf = rhs;
lhs = rhs;
++leafcnt;
}
lhsbest = NULL;
rhsbest = NULL;
do {
if (leafcnt == 1) {
bestcost = leafbase->depth;
lhsbest = leafbase;
break;
}
for (lhs = leafbase; lhs != NULL; lhs = lhs->leaf) {
nodeshow(lhs,"LEAFLHS");
for (rhs = lhs->leaf; rhs != NULL; rhs = rhs->leaf) {
curcost = pathcost(lhs,rhs);
if (curcost > bestcost) {
lhsbest = lhs;
nodeshow(lhsbest,"LHSGUD");
rhsbest = rhs;
nodeshow(rhsbest,"RHSGUD");
bestcost = curcost;
}
}
}
} while (0);
nodeshow(lhsbest,"LHSBEST");
nodeshow(rhsbest,"RHSBEST");
soldepth = bestcost;
}
int
pathcost2(node_t *lhs,node_t *rhs)
{
int lhsok;
int rhsok;
int cost;
dbgprt("pathcost2: ENTER lhs=%d rhs=%d xid=%s\n",
nodenum(lhs),nodenum(rhs),nodexid(lhs,rhs));
cost = 0;
if (lhs == root) {
dbgprt("pathcost: QWKROOT\n");
cost = rhs->depth;
lhs = NULL;
rhs = NULL;
}
while (1) {
if ((lhs == NULL) && (rhs == NULL))
break;
// join at lower level than root
if (lhs == rhs)
break;
#ifdef DEBUG
nodeshow(lhs,"LHS");
nodeshow(rhs,"RHS");
#endif
lhsok = pathok(lhs);
rhsok = pathok(rhs);
if (PTROK(lhs) && PTROK(rhs) && (lhs->depth > rhs->depth)) {
//nodeshow(lhs,"LHSDEEP");
if (lhsok) {
cost += 1;
dbgprt("pathcost: LCOST/D cost=%d\n",cost);
lhs = lhs->parent;
}
continue;
}
if (PTROK(lhs) && PTROK(rhs) && (rhs->depth > lhs->depth)) {
//nodeshow(lhs,"RHSDEEP");
if (rhsok) {
cost += 1;
dbgprt("pathcost: RCOST/D cost=%d\n",cost);
rhs = rhs->parent;
}
continue;
}
if (PTROK(lhs) && lhsok) {
cost += 1;
dbgprt("pathcost: LCOST/S cost=%d\n",cost);
lhs = lhs->parent;
}
if (PTROK(rhs) && rhsok) {
cost += 1;
dbgprt("pathcost: RCOST/S cost=%d\n",cost);
rhs = rhs->parent;
}
}
dbgprt("pathcost2: EXIT cost=%d\n",cost);
return cost;
}
void
search2(void)
{
int curcost;
node_t *end = &nodelist[Acnt];
node_t *leafbase = NULL;
node_t *lhs = NULL;
node_t *rhs = NULL;
int bestcost = 0;
int leafcnt = 0;
int maxdepth = 0;
lhsbest = NULL;
rhsbest = NULL;
// link all leaf nodes together
for (rhs = nodelist; rhs < end; ++rhs) {
if (rhs->cldhead != NULL)
continue;
nodeshow(rhs,"ISLEAF");
if (rhs->depth > maxdepth) {
maxdepth = rhs->depth;
rhsbest = rhs;
}
if (leafbase == NULL)
leafbase = rhs;
if (lhs != NULL)
lhs->leaf = rhs;
lhs = rhs;
++leafcnt;
}
do {
bestcost = maxdepth;
lhsbest = leafbase;
if (leafcnt == 1) {
bestcost = leafbase->depth;
lhsbest = leafbase;
break;
}
for (lhs = leafbase; lhs != NULL; lhs = lhs->leaf) {
nodeshow(lhs,"LEAFLHS");
for (rhs = lhs->leaf; rhs != NULL; rhs = rhs->leaf) {
curcost = pathcost(lhs,rhs);
if (curcost > bestcost) {
lhsbest = lhs;
nodeshow(lhsbest,"LHSGUD");
rhsbest = rhs;
nodeshow(rhsbest,"RHSGUD");
bestcost = curcost;
}
}
}
} while (0);
nodeshow(lhsbest,"LHSBEST");
nodeshow(rhsbest,"RHSBEST");
soldepth = bestcost;
}
void
dograph(void)
{
#ifdef GRAPH
int idx;
node_t *cur;
node_t *par;
char *bp;
char buf[100];
xfgrf = fopen("grf","w");
fprintf(xfgrf,"digraph {\n");
for (idx = 0; idx < Acnt; ++idx) {
cur = &nodelist[idx];
bp = buf;
bp += sprintf(bp,"label=\"N%d D%d\"",nodenum(cur),cur->depth);
if (cur == rhsbest)
bp += sprintf(bp," color=Green");
if (cur == lhsbest)
bp += sprintf(bp," color=Red");
fprintf(xfgrf,"\tN%d [%s]\n",nodenum(cur),buf);
par = cur->parent;
if (par != NULL)
fprintf(xfgrf,"\tN%d -> N%d\n",nodenum(par),nodenum(cur));
}
fprintf(xfgrf,"}\n");
fclose(xfgrf);
#endif
}
int
solve(int *A,int argcnt)
{
int idx;
int parval;
node_t *par;
if (root != NULL) {
memset(nodelist,0,sizeof(nodelist));
root = NULL;
}
// find the root node
// FIXME/CAE -- probably always the first
Acnt = argcnt;
for (idx = 0; idx < Acnt; ++idx) {
int parval = A[idx];
if (parval == -1) {
dbgprt("solve: ROOT idx=%d\n",idx);
root = newnode(idx,NULL);
break;
}
}
// build all child nodes:
for (idx = 0; idx < Acnt; ++idx) {
parval = A[idx];
if (parval == -1)
continue;
dbgprt("solve: NODE idx=%d parval=%d\n",idx,parval);
// find parent
par = fastfind(parval);
// create node
node_t *cur = newnode(idx,par);
// attach child to parent
addchild(par,cur);
}
// traverse all nodes in the tree to find max distance ...
search2();
dograph();
return soldepth;
}

I get a pointer with 0xCDCDCDCD problem when printing out data tree, C

I get a pointer with 0xCDCDCDCD when I want to print a tree but no problem when I want to print a queue in the almost same code
I write a queue by a c program and revise it to print as a tree , that queue was successful printed but when I tried to print the tree my visual studio told me there was a 0xCDCDCDCD problem.
this is the previous version that ran well.
#include<stdio.h>
#include<stdlib.h>
typedef struct _node
{
long long value;
//int value
struct _node *next;
}Node;
typedef struct _Queue
{
Node *head;
Node *tail;
}Queue;
Queue* init_queue()
{
Queue *queue=(Queue*)malloc(sizeof(Queue));
queue->head = queue->tail = NULL;
return queue;
}
void enQueue(Queue *pQueue,Node *pNode)
{
if(pQueue->head == NULL)
{//when it's empty
pQueue->head = pNode;
pQueue->tail = pNode;
}
else
{
pQueue->tail->next = pNode;
pQueue->tail = pNode;
}
}
int deQueue(Queue *pQueue)
{
int i;
if(pQueue->head == NULL)
{
return NULL;
}
// Node *deNode;
//Node *tmp;
//Node *deNode;
//deNode= pQueue->head;
Node *deNode= pQueue->head;
//Node *tmp= pQueue->head;
i=deNode->value;
pQueue->head= pQueue->head->next;
//free(deNode);
return i;
}
Node* init_node(int value)
{
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->value=value;
return new_node;
}
//0:empty
int ifEmpty(Queue *pQueue)
{
if(pQueue->head == NULL)
{
printf("empty tree\n");
return 0;
}
printf("queue is not empty\n");
return 1;
}
int main()
{
Queue *queue=init_queue();
int i;
ifEmpty(queue);
printf("insert node to queue\n");
for(i=0; i<7;i++)
{
Node *node = init_node(i);
enQueue(queue,node);
// free(node);
}
// Node *node = init_node(1);
// printf("node->value = %d\n",node->value);
// enQueue(queue,node);
ifEmpty(queue);
for(i=0;i<7;i++)
{
int deNode = deQueue(queue);
//if(!deNode)
//{
//printf("NULL\n");
//}
//else
//{
printf("deNode->value = %d\n",deNode);
//}
}
//int deNode = deQueue(queue);
//free(queue);
// printf("\n after free deNode->value = %d\n",queue->head->value);
ifEmpty(queue);
return 0;
}
I want to change this into a tree format but my visual studio told me there was a 0xCDCDCDCD problem. below are my codecs:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define NUM 6
typedef struct _node
{
int value;
struct _node *left;
struct _node *right;
}TNode,*Tree;
//add a *next in q_node is my purpose
//other wise , we need to add in the Tree node struct
//So, for the sake of doesn't modify the struct of tree
//I design a q_node struct to include it
//we can use define command to make it as a template.
typedef struct _q_node
{
TNode *t_node;
int depth;
int blank; //0: means correspoinding tree node is not NULL(default)
struct _q_node *next;
}QNode;
typedef struct _Queue
{
QNode *head;
QNode *tail;
}Queue;
Queue* init_queue()
{
Queue *queue=(Queue*)malloc(sizeof(Queue));
queue->head = queue->tail = NULL;
return queue;
}
int enQueue(Queue *pQueue,TNode *pTNode,int pDepth)
{
QNode *pQNode = (QNode *)malloc(sizeof(QNode));
pQNode->depth = pDepth;
pQNode->blank = 0; //default config
if(pTNode==NULL)
{
//change default setting; 1 means it's blank QNode
pQNode->blank =1;
}
pQNode->t_node= pTNode;
if(pQueue->head == NULL)
{//when it's empty
pQueue->head = pQNode;
pQueue->tail = pQNode;
}
else
{
pQueue->tail->next = pQNode;
pQueue->tail = pQNode;
}
}
QNode* deQueue(Queue *pQueue)
{
if(pQueue->head == NULL)
{
return NULL;
}
QNode *deNode= pQueue->head;
pQueue->head = pQueue->head->next;
//pQueue->head = pQueue->head->next;
//deNode = deNode->next;
return deNode;
}
TNode* init_TNode(int value)
{
TNode *new_node = (TNode*)malloc(sizeof(TNode));
new_node->value=value;
new_node->left = new_node->right = NULL;
return new_node;
}
//0:empty
int ifEmpty(Queue *pQueue)
{
if(pQueue->head == NULL)
{
//printf("empty tree\n");
return 0;
}
//printf("queue is not empty\n");
return 1;
}
int insert_tree(Tree pTree,int pValue)
{
//found NULL sub tree, then add to his father->left
if(!pTree)
{
return 0;
}
TNode *tNode = init_TNode(pValue);
if(tNode==NULL)
{
printf("create TNode error!\n");
return 0;
}
if(pValue < pTree->value)
if(insert_tree(pTree->left,pValue)==0)
{
//no left child any more,set a new left child to pTree
pTree->left = tNode;
printf("insert :%d\n",pValue);
}
if(pValue > pTree->value)
if(insert_tree(pTree->right,pValue)==0)
{
pTree->right = tNode;
printf("insert :%d\n",pValue);
}
}
Tree creatTree(int num)
{
srand(time(NULL));
Tree root = init_TNode(rand()%100);
printf("root is %d\n",root->value);
int i ;
for(i=1;i<num;i++)
{
insert_tree(root,rand()%100);
}
printf("creat tree succuess!Tree heigh is:%d\n",get_tree_height(root));
return root ;
}
int get_tree_height(Tree pRoot)
{
if(!pRoot)
{
return 0;
}
int lh=0,rh=0;
lh = get_tree_height(pRoot->left);
rh = get_tree_height(pRoot->right);
return (lh<rh)?(rh+1):(lh+1);
}
int breath_travel(Tree pRoot,Queue *pQueue)
{
int height = get_tree_height(pRoot);
int pad_num = 3;
//compare to the node's depth in the "while loop"
int current_depth = 1;
if(!pRoot)
{
return 0;
}
enQueue(pQueue,pRoot,1);
printf("_______________________\n");
printf("breath begin,enter root:\n");
while(ifEmpty(pQueue)!=0)
{
QNode *qNode = deQueue(pQueue);
//the sub node's depth is 1 more then the parent's
int child_depth = qNode->depth + 1 ;
if(qNode->depth > current_depth)
{
current_depth = qNode->depth;
printf("\n\n");
}
// ***************0**************** pad_between = 31 ; pad_front = 15 (depth == 1)
// *******0***************0******** pad_between = 15 ; pad_front = 7 (depth == 2)
// ***0*******0*******0*******0**** pad_between = 7 ; pad_front = 3 (depth == 3)
// *0***0***0***0***0***0***0***0** pad_between = 3 ; pad_front = 1 (depth == 4)
// 0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0* pad_between = 1 ; pad_front = 0; (depth == 5)
// Tree height = 5
// pad_num = 1
// padding between node = (1+2*pad_front)*pad_num = (1+ (1<<(height-depth))-1)*pad_num
// (1<< (height - current_depth))-1=2^(height - current_depth)-1
int pad_front = (1<< (height - current_depth))-1;
if((qNode->blank == 1))
{
//add the parent node's padding:2
if(pad_front == 0) printf("%*s%*s",pad_num,"o",pad_num," ");
else printf("%*s%*s%*s",pad_front*pad_num," ",pad_num,"o",(1+pad_front)*pad_num," ");
//pad_front*pad_num+(1+pad_front)*pad_num=(1+2*pad_front)*pad_num=padding between node
if(child_depth <= height)
{
//enter two NULL sub-tree node.
//every time you enter NULL TNode,there's corresponding blank QNode.
enQueue(pQueue,NULL,child_depth);
enQueue(pQueue,NULL,child_depth);
}
}
else
{
if(pad_front == 0) printf("%*d%*s",pad_num,qNode->t_node->value,pad_num," ");
else printf("%*s%*d%*s",pad_front*pad_num," ",pad_num,qNode->t_node->value,(1+pad_front)*pad_num," ");
if(child_depth <=height)
{
enQueue(pQueue,qNode->t_node->left,child_depth);
enQueue(pQueue,qNode->t_node->right,child_depth);
}
}
} //while end
printf("\n-----------\nbreath end!\n-----------\n");
return 1;
}
int main(int argc,char **argv)
{
Queue *queue=init_queue();
int i;
ifEmpty(queue);
printf("insert node to queue\n");
int num = NUM; //default
if(argc == 2)
{
num = atoi(argv[1]);
}
Tree root = creatTree(num);
if(!root)
{
printf("create Tree failed!\n");
return 0;
}
breath_travel(root,queue);
return 0;
}
the problem is in the deQueue function when I want to print the tree my visual studio told me " pQueue->head= pQueue->head->next;" this line had a 0xCDCDCDCD
problem in the deQueue function I don't know why I even tried to put all this funtion in the main function but the problem was still there:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define NUM 6
typedef struct _node
{
int value;
struct _node *left;
struct _node *right;
}TNode, *Tree;
//add a *next in q_node is my purpose
//other wise , we need to add in the Tree node struct
//So, for the sake of doesn't modify the struct of tree
//I design a q_node struct to include it
//we can use define command to make it as a template.
typedef struct _q_node
{
TNode *t_node;
int depth;
int blank; //0: means correspoinding tree node is not NULL(default)
struct _q_node *next;
}QNode;
typedef struct _Queue
{
QNode *head;
QNode *tail;
}Queue;
Queue* init_queue()
{
Queue *queue = (Queue*)malloc(sizeof(Queue));
queue->head = queue->tail = NULL;
return queue;
}
int enQueue(Queue *pQueue, TNode *pTNode, int pDepth)
{
QNode *pQNode = (QNode *)malloc(sizeof(QNode));
pQNode->depth = pDepth;
pQNode->blank = 0; //default config
if (pTNode == NULL)
{
//change default setting; 1 means it's blank QNode
pQNode->blank = 1;
}
pQNode->t_node = pTNode;
if (pQueue->head == NULL)
{//when it's empty
pQueue->head = pQNode;
pQueue->tail = pQNode;
}
else
{
pQueue->tail->next = pQNode;
pQueue->tail = pQNode;
}
}
/*QNode* deQueue(Queue *pQueue)
{
if (pQueue->head == NULL)
{
return NULL;
}
QNode *deNode = pQueue->head;
pQueue->head = pQueue->head->next;
//pQueue->head = pQueue->head->next;
//deNode = deNode->next;
return deNode;
}
*/
TNode* init_TNode(int value)
{
TNode *new_node = (TNode*)malloc(sizeof(TNode));
new_node->value = value;
new_node->left = new_node->right = NULL;
return new_node;
}
//0:empty
int ifEmpty(Queue *pQueue)
{
if (pQueue->head == NULL)
{
//printf("empty tree\n");
return 0;
}
//printf("queue is not empty\n");
return 1;
}
int insert_tree(Tree pTree, int pValue)
{
//found NULL sub tree, then add to his father->left
if (!pTree)
{
return 0;
}
TNode *tNode = init_TNode(pValue);
if (tNode == NULL)
{
printf("create TNode error!\n");
return 0;
}
if (pValue < pTree->value)
if (insert_tree(pTree->left, pValue) == 0)
{
//no left child any more,set a new left child to pTree
pTree->left = tNode;
printf("insert :%d\n", pValue);
}
if (pValue > pTree->value)
if (insert_tree(pTree->right, pValue) == 0)
{
pTree->right = tNode;
printf("insert :%d\n", pValue);
}
}
Tree creatTree(int num)
{
srand((unsigned)time(NULL));
Tree root = init_TNode(rand() % 100);
printf("root is %d\n", root->value);
int i;
for (i = 1; i < num; i++)
{
insert_tree(root, rand() % 100);
}
printf("creat tree succuess!Tree heigh is:%d\n", get_tree_height(root));
return root;
}
int get_tree_height(Tree pRoot)
{
if (!pRoot)
{
return 0;
}
int lh = 0, rh = 0;
lh = get_tree_height(pRoot->left);
rh = get_tree_height(pRoot->right);
return (lh < rh) ? (rh + 1) : (lh + 1);
}
/*
int breath_travel(Tree pRoot, Queue *pQueue)
{
int height = get_tree_height(pRoot);
int pad_num = 3;
//compare to the node's depth in the "while loop"
int current_depth = 1;
if (!pRoot)
{
return 0;
}
enQueue(pQueue, pRoot, 1);
printf("_______________________\n");
printf("breath begin,enter root:\n");
while (ifEmpty(pQueue) != 0)
{
//QNode *qNode = deQueue(pQueue);
//the sub node's depth is 1 more then the parent's
if (pQueue->head == NULL)
{
return NULL;
}
QNode *qNode = pQueue->head;
pQueue->head = pQueue->head->next;
int child_depth = qNode->depth + 1;
if (qNode->depth > current_depth)
{
current_depth = qNode->depth;
printf("\n\n");
}
// ***************0**************** pad_between = 31 ; pad_front = 15 (depth == 1) 一共31个*
// *******0***************0******** pad_between = 15 ; pad_front = 7 (depth == 2)
// ***0*******0*******0*******0**** pad_between = 7 ; pad_front = 3 (depth == 3)
// *0***0***0***0***0***0***0***0** pad_between = 3 ; pad_front = 1 (depth == 4)
// 0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0* pad_between = 1 ; pad_front = 0; (depth == 5)
// Tree height = 5
// pad_num = 1
// padding between node = (1+2*pad_front)*pad_num = (1+ (1<<(height-depth))-1)*pad_num
// (1<< (height - current_depth))-1=2^(height - current_depth)-1
int pad_front = (1 << (height - current_depth)) - 1;
if ((qNode->blank == 1))
{
//add the parent node's padding:2
if (pad_front == 0) printf("%*s%*s", pad_num, "o", pad_num, " ");
else printf("%*s%*s%*s", pad_front*pad_num, " ", pad_num, "o", (1 + pad_front)*pad_num, " ");
//pad_front*pad_num+(1+pad_front)*pad_num=(1+2*pad_front)*pad_num=padding between node
if (child_depth <= height)
{
//enter two NULL sub-tree node.
//every time you enter NULL TNode,there's corresponding blank QNode.
enQueue(pQueue, NULL, child_depth);
enQueue(pQueue, NULL, child_depth);
}
}
else
{
if (pad_front == 0) printf("%*d%*s", pad_num, qNode->t_node->value, pad_num, " ");
else printf("%*s%*d%*s", pad_front*pad_num, " ", pad_num, qNode->t_node->value, (1 + pad_front)*pad_num, " ");
if (child_depth <= height)
{
enQueue(pQueue, qNode->t_node->left, child_depth);
enQueue(pQueue, qNode->t_node->right, child_depth);
}
}
} //while end
printf("\n-----------\nbreath end!\n-----------\n");
return 1;
}
*/
int main(int argc, char **argv)
{
Queue *pQueue = init_queue();
int i;
ifEmpty(pQueue);
printf("insert node to queue\n");
int num = NUM; //default
if (argc == 2)
{
num = atoi(argv[1]);
}
Tree pRoot = creatTree(num);
if (!pRoot)
{
printf("create Tree failed!\n");
return 0;
}
//breath_travel(root, queue);
int height = get_tree_height(pRoot);
int pad_num = 3;
//compare to the node's depth in the "while loop"
int current_depth = 1;
if (!pRoot)
{
return 0;
}
enQueue(pQueue, pRoot, 1);
printf("_______________________\n");
printf("breath begin,enter root:\n");
while (ifEmpty(pQueue) != 0)
{
//QNode *qNode = deQueue(pQueue);
//the sub node's depth is 1 more then the parent's
if (pQueue->head == NULL)
{
return NULL;
}
QNode *qNode = pQueue->head;
pQueue->head = pQueue->head->next;
int child_depth = qNode->depth + 1;
if (qNode->depth > current_depth)
{
current_depth = qNode->depth;
printf("\n\n");
}
// ***************0**************** pad_between = 31 ; pad_front = 15 (depth == 1)
// *******0***************0******** pad_between = 15 ; pad_front = 7 (depth == 2)
// ***0*******0*******0*******0**** pad_between = 7 ; pad_front = 3 (depth == 3)
// *0***0***0***0***0***0***0***0** pad_between = 3 ; pad_front = 1 (depth == 4)
// 0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0* pad_between = 1 ; pad_front = 0; (depth == 5)
// Tree height = 5
// pad_num = 1
// padding between node = (1+2*pad_front)*pad_num = (1+ (1<<(height-depth))-1)*pad_num
// (1<< (height - current_depth))-1=2^(height - current_depth)-1
int pad_front = (1 << (height - current_depth)) - 1;
if ((qNode->blank == 1))
{
//add the parent node's padding:2
if (pad_front == 0) printf("%*s%*s", pad_num, "o", pad_num, " ");
else printf("%*s%*s%*s", pad_front*pad_num, " ", pad_num, "o", (1 + pad_front)*pad_num, " ");
//pad_front*pad_num+(1+pad_front)*pad_num=(1+2*pad_front)*pad_num=padding between node
if (child_depth <= height)
{
//enter two NULL sub-tree node.
//every time you enter NULL TNode,there's corresponding blank QNode.
enQueue(pQueue, NULL, child_depth);
enQueue(pQueue, NULL, child_depth);
}
}
else
{
if (pad_front == 0) printf("%*d%*s", pad_num, qNode->t_node->value, pad_num, " ");
else printf("%*s%*d%*s", pad_front*pad_num, " ", pad_num, qNode->t_node->value, (1 + pad_front)*pad_num, " ");
if (child_depth <= height)
{
enQueue(pQueue, qNode->t_node->left, child_depth);
enQueue(pQueue, qNode->t_node->right, child_depth);
}
}
} //while end
printf("\n-----------\nbreath end!\n-----------\n");
return 0;
}

Binary tree implementation C

The 't' pointer in the insert() function is set to NULL every time I call the insert function. Is it something to do with messing up of pointers?
int main() {
int num, i;
tree *t;
t = NULL;
for(i = 0; i < 5; i++) {
scanf("%d", &num);
insert(t, num);
}
//inorder(t);
return 0;
}
The insert function is as follows:
void insert(tree *t, int num) {
int flag;
tree *p, *q;
tree *temp = (tree *)malloc(sizeof(tree));
temp->data = num;
temp->left = NULL;
temp->right = NULL;
if(t == NULL) {
t = temp;
printf("Hello");
return;
}
printf("%d", t->data);
p = t;
while(p) {
q = p;
if(p->data <= num) {
p = p->right;
flag = 1;
}
else {
p = p->left;
flag = 0;
}
if(flag == 1)
q->right = temp;
else
q->left = temp;
}
}
My tree structure is as follows :
typedef struct tree {
int data;
struct tree *left, *right;
}tree;

Resources