Binary searching in tree - c

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.

Related

What can I do to make my code generate an output?

#include <stdio.h>
#include <stdlib.h>
typedef enum TypeTag {
ADD,
SUB,
MUL,
DIV,
ABS,
FIB,
} TypeTag;
typedef struct Node {
TypeTag type;
int value;
struct Node *left;
struct Node *right;
} Node;
#define MAXN 100
int fib[MAXN];
// function to create a new node
Node* makeFunc(TypeTag type) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->type = type;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// fibonacci function using dynamic programming
int fibonacci(int n) {
int fib[n+1];
fib[0] = 0;
fib[1] = 1;
for(int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
}
// function to calculate the value of a node
int calc(Node* node) {
if (node->type == ADD) {
return calc(node->left) + calc(node->right);
}
else if (node->type == SUB) {
return calc(node->left) - calc(node->right);
}
else if (node->type == MUL) {
return calc(node->left) * calc(node->right);
}
else if (node->type == DIV) {
return calc(node->left) / calc(node->right);
}
else if (node->type == ABS) {
return abs(calc(node->left));
}
else if (node->type == FIB) {
return fibonacci(calc(node->left));
}
return node->value;
}
int main() {
for (int i = 0; i < MAXN; i++) {
fib[i] = -1;
}
Node *add = makeFunc(ADD);
add->left = makeFunc(10);
add->right = makeFunc(6);
Node *mul = makeFunc(MUL);
mul->left = makeFunc(5);
mul->right = makeFunc(4);
Node *sub = makeFunc(SUB);
sub->left = makeFunc(calc(add));
sub->right = makeFunc(calc(sub));
Node *fibo = makeFunc(FIB);
fibo->left = makeFunc(abs(calc(sub)));
fibo->value = fibonacci(calc(fibo->left));
printf("add : %d\n", calc(add));
printf("mul : %d\n", calc(mul));
printf("sub : %d\n", calc(sub));
printf("fibo : %d\n", calc(fibo));
printf("Hello world");
// return 0;
}
I think the problem is coming from the makeFunc function but i am not sure what else to do.I tried to print hello world to see if the problem is from my implementations but it still did not print.
I was trying to solve this problem
{
TypeTag type;
} Node;
typedef enum TypeTag {
...
}
Using this structure, please write a function that returns fibonacci sequence based on the following arithmetic operations (+, -,
*, /) and conditions. The fibonacci function should be implemented using Dynamic Programming.
main()
{
Node *add = (*makeFunc(ADD))(10, 6);
Node *mul = (*makeFunc(MUL))(5, 4);
Node *sub = (*makeFunc(SUB))(mul, add);
Node *fibo = (*makeFunc(SUB))(sub, NULL);
calc(add);
calc(mul);
calc(sub);
calc(fibo)
}
Output
add : 16
mul : 20
sub : -4
fibo : 2
You can't use makeFunc(4) to make the representation of the number 4, because 4 == ABS. You should use a separate type for nodes that represent numbers rather than functions. Then use another function to create nodes of this type.
Another problem is here:
sub->right = makeFunc(calc(sub));
You can't call calc(sub) until after you've filled in both sub->left and sub->right. I'm guessing you meant to use calc(mul).
#include <stdio.h>
#include <stdlib.h>
typedef enum TypeTag {
ADD,
SUB,
MUL,
DIV,
ABS,
FIB,
LIT
} TypeTag;
typedef struct Node {
TypeTag type;
int value;
struct Node *left;
struct Node *right;
} Node;
#define MAXN 100
int fib[MAXN];
// function to create a new node
Node* makeFunc(TypeTag type) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->type = type;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
Node* makeValue(int value) {
Node *newNode = makeFunc(LIT);
newNode->value = value;
return newNode;
}
// fibonacci function using dynamic programming
int fibonacci(int n) {
int fib[n+1];
fib[0] = 0;
fib[1] = 1;
for(int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
}
// function to calculate the value of a node
int calc(Node* node) {
if (node->type == ADD) {
return calc(node->left) + calc(node->right);
}
else if (node->type == SUB) {
return calc(node->left) - calc(node->right);
}
else if (node->type == MUL) {
return calc(node->left) * calc(node->right);
}
else if (node->type == DIV) {
return calc(node->left) / calc(node->right);
}
else if (node->type == ABS) {
return abs(calc(node->left));
}
else if (node->type == FIB) {
return fibonacci(calc(node->left));
}
else if (node->type == LIT) {
return node->value;
}
printf("Invalid node type %d\n", node->type);
exit(1);
}
int main() {
for (int i = 0; i < MAXN; i++) {
fib[i] = -1;
}
Node *add = makeFunc(ADD);
add->left = makeValue(10);
add->right = makeValue(6);
Node *mul = makeFunc(MUL);
mul->left = makeValue(5);
mul->right = makeValue(4);
Node *sub = makeFunc(SUB);
sub->left = makeValue(calc(add));
sub->right = makeValue(calc(mul));
Node *fibo = makeFunc(FIB);
fibo->left = makeValue(abs(calc(sub)));
fibo->value = fibonacci(calc(fibo->left));
printf("add : %d\n", calc(add));
printf("mul : %d\n", calc(mul));
printf("sub : %d\n", calc(sub));
printf("fibo : %d\n", calc(fibo));
printf("Hello world\n");
// return 0;
}

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;
}

create an array with the values of the nodes at a level

I have to create an array that contains the values of nodes in a level passed as parameter. The function createArray has to return an array containing the values of the nodes at the level passed as parameter. My code is:
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data) {
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
int numNodesLevel(struct node* root, int level) {
if (root == NULL) {
return 0;
}
else {
if (level == 0) {
return 1;
}
return numNodesLevel(root->left, level - 1) + numNodesLevel(root->right, level - 1);
}
}
int max(int a, int b) {
if(a > b) {
return a;
}
else {
return b;
}
}
int height(struct node* root) {
if (root == NULL) {
return -1;
}
else {
if (root->left == NULL && root->right == NULL) {
return 0;
}
return max(height(root->left), height(root->right)) + 1;
}
}
int maxNodesLevel(struct node* root) {
if (root == NULL) {
return 0;
}
else {
int max = 0;
int h = height(root);
int i = 0;
for (i = 0; i <= h; i++) {
if (numNodesLevel(root, i) > max) {
max = numNodesLevel(root, i);
}
}
return max;
}
}
void fill(struct node* root, int* A, int level, int* i) {
if (root != NULL) {
if (level == 0) {
A[*i] = root->data;
*i = *i + 1;
}
fill(root->left, A, level - 1, i);
fill(root->right, A, level - 1, i);
}
}
int* createArray(struct node* root, int level) {
if (root != NULL) {
int *A = (int*)calloc(maxNodesLevel(root), sizeof(int));
int i = 0;
fill(root, A, level, &i);
return A;
}
}
int main(){
struct node* root = newNode(12);
root->left = newNode(3);
root->right = newNode(16);
root->left->left = newNode(2);
root->left->right = newNode(2);
root->right->left = newNode(2);
root->right->right = newNode(22);
printf("%d", createArray(root,1));
getchar();
return 0;
}
The result should be 3,16 which are the values of the nodes at level 1, but it gives me different numbers like 22721648. These numbers are different every time I run the code, so I think there must be something wrong in the way I use pointers, but I can't figure out where is the error.
Can somebody help me?
The code is correct, but only mistake here is createArray() returns an array and you are considering it as int.
Add following code instead of printf() and it will work.
int level = 1, *arr;
arr = createArray(root, level);
for(int i = 0; i < 2 * level; i++){
printf("%d ", arr[i]);
}
Hope it will help !!

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.

Resources