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

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 !!

Related

Problem searching in my Binary Search Tree

Problem is function bin_search. it works steady on function insert. However, it gets frozen on function search. I think if it's fine on insert, it should be fine on search, but it isn't. Here is my code...
"bst.h":
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int key;
void *data;
struct Node *left, *right;
void (*destroy)(void *data);
} node;
typedef struct Tree {
node *head;
char name;
} tree;
#define key(node) node->key
#define data(node) node->data
#define left(node) node->left
#define right(node) node->right
#define destroy(node) node->destroy
#define tree_head(tree) tree->head
"functions.c":
#include "bst.h"
int bin_search(node *curr, int key, int cnt, node **found) {
cnt++; printf("cnt+\n");
if (curr == NULL) {
return -1;
} else if (curr->key == key) {
printf("curr_key = key\n"); return cnt;
}
if (curr->key < key) {
printf("curr_key < key\n");
if (curr->right == NULL) {
*found = curr;
return -(cnt + 1);
}
return bin_search(curr->right, key, cnt, found);
} else {
printf("curr_key > key\n");
if (curr->left == NULL) {
*found = curr;
return -(cnt + 1);
}
return bin_search(curr->left, key, cnt, found);
}
}
int insert(tree *root, int key, void *data, void (*destroy)(void *data)) {
if (root->head == NULL) {
node* new_node = (node *)malloc(sizeof(node));
left(new_node) = NULL; right(new_node) = NULL; destroy(new_node) = destroy; key(new_node) = key; data(new_node) = data;
tree_head(root) = new_node;
printf("created first node\n"); return 1;
}
int cnt; node **found;
if ((cnt = bin_search(root->head, key, 0, found)) < 0) {
node* new_node = (node *)malloc(sizeof(node));
left(new_node) = NULL; right(new_node) = NULL; destroy(new_node) = destroy; key(new_node) = key; data(new_node) = data;
if ((*found)->key < key) {
(*found)->right = new_node;
} else {
(*found)->left = new_node;
}
printf("created a node at %d\n", -cnt); return 1;
} else {
printf("already exists in tree"); return -1;
}
}
int search(tree *root, int key, void **data) {
if (root->head == NULL) {
printf("tree is empty\n"); return -1;
}
int cnt; node **found;
if ((cnt = bin_search(root->head, key, 0, found)) < 0) {
return -1;
} else {
if ((*found)->key < key) {
*data = (*found)->right->data;
} else {
*data = (*found)->left->data;
}
return cnt;
}
}
"main.c":
#include "bst.h"
#define MAX_NUM 8
#define MAX_LEGNTH 200
int main() {
// create a tree
tree root; root.head = NULL; root.name = 'a';
FILE *inpt = fopen("list.txt", "r"); char buffer[MAX_LEGNTH];
int count = 0;
while (fgets(buffer, MAX_LEGNTH, inpt) != NULL) {
printf("adding: %d\n", atoi(buffer)); insert(&root, atoi(buffer), buffer, NULL);
count++;
}
fclose(inpt);
int result; void **found;
result = search(&root, 2, found); printf("%d\n", result); // problem in here!!
return 0;
}
what is the problem with my 'search' function. I can't find it.
Besides the utterly non-standard use of sizeof(void), you are not providing a correct out-parameter to search. The point of the found argument is to receive the node pointer if the prospect key was discovered. This...
int cnt;
node **found; // <== LOOK HERE
if ((cnt = bin_search(root->head, key, 0, found)) < 0) {
is not the way to do that. It should be done like this:
int cnt;
node *found = NULL;
if ((cnt = bin_search(root->head, key, 0, &found)) < 0) {
// ^^^^^^
and all references to found thereafter should be through found->, not (*found)->
This mistake is made in three different places in your code. The last one is semi-broken, but still broken nonetheless.
void **found = (void *)malloc(sizeof(void));
int result = search(&root, 2, found);
printf("%d\n", result);
That should use this:
void *found = NULL;
int result = search(&root, 2, &found);
printf("%d\n", result);
Whether the rest of your code is broken I cannot say, and frankly we're not in the business of being an online-debugger. Use your local debugger tools; that's what they're for. But the items listed above are definitely a problem.

How can I get a non-empty binary tree and print it?

I built three files, which includes MainFunc.c, AllFun.h, and OtheFunc.c.
The program happens runtime error, which print nothing. However, I need it output a tree as previous order.
I guess the problem may be that I built an empty tree, but I can't solve it.
MainFunc.c
#include "AllFun.h"
int main(int argc, char* argv[])
{
int nums[MaxSize] = { 0 };
printf("Enter value of root node: ");
for (int i = 0; i < MaxSize; ++i) {
scanf_s("%d", &nums[i]);
}
TreeNode* root = create(nums, MaxSize);
preorder(root);
return 0;
}
AllFun.h
#include <stddef.h> // NULL
#include <stdlib.h>
#include <stdio.h>
#define MaxSize 10
typedef struct node {
int data;
struct node* lchild, * rchild;
} TreeNode;
TreeNode *create(int nums[], int n);
void preorder(TreeNode *root);
OtheFunc.c
#include "AllFun.h"
TreeNode* newNode(int v) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
if (node) {
node->data = v;
node->lchild = node->rchild = NULL;
return node;
}
}
void insert(TreeNode* root, int x)
{
if (root == NULL) {
root = newNode(x);
return;
}
if (root->data < x) {
insert(root->lchild, x);
}
else {
insert(root->rchild, x);
}
}
TreeNode *create(int nums[], int n)
{
TreeNode* root = NULL; // Build a empty root node
for (int i = 0; i < n; i++) {
insert(root, nums[i]);
}
return root;
}
void preorder(TreeNode* root)
{
if (root == NULL) {
return;
}
printf("%d ", root->data);
preorder(root->lchild);
preorder(root->rchild);
}
You have to pass the node as a pointer to pointer, then the function can change the pointer:
void insert(TreeNode** root, int x)
{
if (*root == NULL) {
*root = newNode(x);
return;
}
if ((*root)->data < x) {
insert(&(*root)->lchild, x);
}
else {
insert(&(*root)->rchild, x);
}
}
Call with insert(&root, nums[i]);:
https://ideone.com/nV5q1g

Unknown NULL value accessed

this a partial program of AVL tree, but right now its just more of a BST
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
typedef struct node node;
struct node
{
int data;
int height;
node *left;
node *right;
} *root = NULL, *temp = NULL;
int max(int n1, int n2)
{
return n1 > n2 ? n1 : n2;
}
node *new_node(int value)
{
temp = (node *)malloc(sizeof(node));
temp->data = value;
temp->left = NULL;
temp->right = NULL;
temp->height = 0;
return temp;
}
int get_height(node *x)
{
if (x == NULL)
{
return -1;
}
return x->height;
}
node *insert(node *r, int value)
{
if (r == NULL)
{
return new_node(value);
}
else
{
if (value < r->data)
r->left = insert(r->left, value);
else
r->right = insert(r->right, value);
int height = max(get_height(r->left), get_height(r->right)) + 1;
}
void inorder(node *r)
{
if (r == NULL)
return;
inorder(r->left);
printf("node = %d, height = %d\n", r->data, r->height);
inorder(r->right);
}
void main()
{
root = insert(root, 10);
root = insert(root, 20);
inorder(root);
}
The output of this program is following, as I'm not accessing any NULL values -
node = 10, height = 1
node = 20, height = 0
after just adding one line, I'm accessing a NULL value
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
typedef struct node node;
struct node
{
int data;
int height;
node *left;
node *right;
} *root = NULL, *temp = NULL;
int max(int n1, int n2)
{
return n1 > n2 ? n1 : n2;
}
node *new_node(int value)
{
temp = (node *)malloc(sizeof(node));
temp->data = value;
temp->left = NULL;
temp->right = NULL;
temp->height = 0;
return temp;
}
int get_height(node *x)
{
if (x == NULL)
{
return -1;
}
return x->height;
}
node *insert(node *r, int value)
{
if (r == NULL)
{
return new_node(value);
}
else
{
if (value < r->data)
r->left = insert(r->left, value);
else
r->right = insert(r->right, value);
int height = max(get_height(r->left), get_height(r->right)) + 1;
int balance_factor = get_height(r->left)- get_height(r->right); // extra line added
}
}
void inorder(node *r)
{
if (r == NULL)
return;
inorder(r->left);
printf("node = %d, height = %d\n", r->data, r->height);
inorder(r->right);
}
void main()
{
root = insert(root, 10);
root = insert(root, 20);
inorder(root);
}
Now my program is just hanging, its not an infinite call/ loop. It is surely a NULL value access. But how is this even possible?
Debugging by forum/Q&A is never efficient. Use a debugger:
For example at https://onlinegdb.com/S1ZansZNU
Reading symbols from a.out...done.
/usr/share/gdb/gdbinit: No such file or directory.
(gdb) run
Starting program: /home/a.out
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400703 in inorder (r=0xffffffff) at main.c:62
62 inorder(r->left);
(gdb)
r is not NULL, but neither is it a valid address.
The problem is clearly in:
root = insert(root, 10);
when insert does not explicitly return a value
Function insert is not returning any pointer in case of r != NULL collecting a return value when function is not returning anything is undefined behavior.
i.e
root = insert(root, 10);//it is returning valid pointer
root = insert(root, 20);//unknown value copied to root
please update your code as follows,
node *insert(node *r, int value)
{
if (r == NULL)
{
return new_node(value);
}
//rest of the logic
return r;//missing from both of your snippet
}
Refer for more details on UB

Having trouble creating an adjacency list

I am trying to represent a graph using an adjacency list, but I am currently struggling with it. For some reason the edges are getting assigned to the wrong vertexes and I can't figure out why. I step through the code and the first 3 vertex pairs are added just fine but for some reason on the 4th nothing works right and I end up creating multiple new edges and not even the values of them are correct. A sample input is below as well as the C code. Anyone know why this might be happening? Note that
void print_distance(vertex*, int);
int check_an_edge(edge*);
void free_head(vertex*);
have not been implemented but free_head is used to free the entire list
5
(2,3)
(1,4)
(1,3)
(3,4)
(4,5)
#include <stdio.h>
#include <stdlib.h>
#include "input_error.h"
#define VertexToSearch 1
typedef struct node {
int value;
struct node* nextedge;
} edge;
typedef struct node1 {
int vertexnumber;
int distance;
struct node* edge;
} vertex;
vertex* load_file(char*);
void create_vertex_list(vertex*, int);
void create_new_edge(int, int, vertex*);
void print_distance(vertex*, int);
int check_an_edge(edge*);
void free_head(vertex*);
enum error program_error;
int main(int argc, char** argv) {
vertex* array;
array = load_file(argv[1]);
free_head(array);
return 0;
}
vertex* load_file(char* filename) {
int count;
int vertex1;
int vertex2;
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("%s did not open", filename);
program_error = FILE_FAILED_TO_OPEN;
exit(program_error);
}
fscanf(file, "%d", &count);
vertex* head = malloc(sizeof(vertex)* count);
create_vertex_list(head, count);
for (int i = 0; i < count; i++) {
fscanf(file, "\n(%d,%d)", &vertex1, &vertex2);
create_new_edge(vertex1, vertex2, head);
}
fclose(file);
return head;
}
void create_vertex_list(vertex head[], int count) {
vertex *new_node;
for (int i = 0; i < count; i++) {
new_node = malloc(sizeof (vertex));
new_node->vertexnumber = i + 1;
new_node->edge = NULL;
new_node->distance = -1;
*(head +i)= *new_node;
}
}
void create_new_edge(int vertex1, int vertex2, vertex* head) {
edge* new = malloc(sizeof (edge));
edge* new1 = malloc(sizeof (edge));
new->value = vertex1;
new1->value = vertex2;
new->nextedge = NULL;
new->nextedge = NULL;
if ((head +vertex1 - 1)->edge == NULL) {
(head +vertex1 - 1)->edge = new1;
} else {
edge* temp = (head +vertex1 - 1)->edge;
while (temp != NULL) {
if (temp->nextedge == NULL) {
temp->nextedge = new1;
break;
} else {
temp = temp->nextedge;
}
}
}
if ((head +vertex2 - 1)->edge == NULL) {
(head +vertex2 - 1)->edge = new;
} else {
edge* temp = (head +vertex2 - 1)->edge ;
while (temp != NULL) {
if (temp->nextedge == NULL) {
temp->nextedge = new1;
break;
} else {
temp = temp->nextedge;
}
}
}
}
In your create_new_edge function in the second if-statement you try to add new1. I think it's a copy-paste bug and you should change it to new.
if ((head +vertex2 - 1)->edge == NULL) {
(head +vertex2 - 1)->edge = new;
} else {
edge* temp = (head +vertex2 - 1)->edge ;
while (temp != NULL) {
if (temp->nextedge == NULL) {
temp->nextedge = new1; // Change here new1 to new
break;
} else {
emp = temp->nextedge;
}
}
}

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