Stuck with branches of Tree - c

i was trying to do tree traversal.(per-order,in-order,and post-order)
here is my code.
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* left;
struct node* right;
};
void Insert(struct node* root,int item)
{
struct node* parent;
struct node* NewNode = (struct node*)malloc(sizeof(struct node));
NewNode->left = NULL;
NewNode->data = item;
NewNode->right = NULL;
if (root == NULL)
root = NewNode;
else
{
parent = root;
while (1)
{
if (parent->data>item)
{
if(parent->left == NULL)
{
parent->left = NewNode;
return;
}
parent = parent->left;
}
if (parent->data<item)
{
if(parent->right == NULL)
{
parent->right = NewNode;
return;
}
parent = parent->right;
}
}
}
}
void pre(struct node *newNode)
{
if(newNode!=NULL)
{
printf("%d ",newNode->data);
pre(newNode->left);
pre(newNode->right);
}
}
void in(struct node *newNode)
{
if(newNode!=NULL)
{
in(newNode->left);
printf("%d ",newNode->data);
in(newNode->right);
}
}
void post(struct node *newNode)
{
if(newNode!=NULL)
{
post(newNode->left);
post(newNode->right);
printf("%d ",newNode->data);
}
}
int main(void)
{
int num,i;
printf("\nHow many Numbers you wanna Enter in tree:\t");
scanf("%d",&num);
int numArr[num];
printf("\nEnter the numbers: \n");
struct node* root = NULL;
for (i=0;i<num;i++)
{
scanf("%d",&numArr[i]);
Insert(root,numArr[i]);
}
printf("\nPre order traversal is:\n");
pre(root);
printf("\nIn order traversal is:\n");
in(root);
printf("\nPost order traversal is:\n");
post(root);
}
i think i have problem with inserting the value because when i run the code the output is just empty.
could anyone explain me where m i going wrong?
at insert function m taking the root node and the item to be inserted as argument.
then i'm creating a new node using malloc.
inserting data to the new node and left, right is null as left and right is currently not pointing to any nodes.
then checking if root is null or not. if it is null m assigning the new node to root node.
if root is not null.
(i should not loose the root so i am copying root to parent and using that.)
m checking if the data is less than root or not. if it is less m going to the left of root if left of root is null m inserting the address of new node there if it is not null m just going left and left until it becomes null.
m doing the same thing(just going right) if data is greater than the value in root.
my explanation tells me m going on the right path.
but my code tell me a different story.

this is the correct answer thanks to everyone for help.
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* left;
struct node* right;
};
void Insert(struct node** root,int item)
{
struct node* parent;
struct node* NewNode = (struct node*)malloc(sizeof(struct node));
NewNode->left = NULL;
NewNode->data = item;
NewNode->right = NULL;
if (*root == NULL)
*root = NewNode;
else
{
parent = *root;
while (1)
{
if (parent->data>item)
{
if(parent->left == NULL)
{
parent->left = NewNode;
return;
}
parent = parent->left;
}
if (parent->data<item)
{
if(parent->right == NULL)
{
parent->right = NewNode;
return;
}
parent = parent->right;
}
}
}
}
void pre(struct node *newNode)
{
if(newNode!=NULL)
{
printf("%d ",newNode->data);
pre(newNode->left);
pre(newNode->right);
}
}
void in(struct node *newNode)
{
if(newNode!=NULL)
{
in(newNode->left);
printf("%d ",newNode->data);
in(newNode->right);
}
}
void post(struct node *newNode)
{
if(newNode!=NULL)
{
post(newNode->left);
post(newNode->right);
printf("%d ",newNode->data);
}
}
int main(void)
{
int num,i;
printf("\nHow many Numbers you wanna Enter in tree:\t");
scanf("%d",&num);
int numArr[num];
printf("\nEnter the numbers: \n");
struct node* root = NULL;
for (i=0;i<num;i++)
{
scanf("%d",&numArr[i]);
Insert(&root,numArr[i]);
}
printf("\nPre order traversal is:\n");
pre(root);
printf("\nIn order traversal is:\n");
in(root);
printf("\nPost order traversal is:\n");
post(root);
}

Related

Unable to understand why my C code runs correctly on Linux and WSL2 but not on pure windows [duplicate]

This question already has answers here:
What exactly is the value contained in an uninitialized local variable in C?
(2 answers)
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 3 months ago.
I have written a code which performs some basic operations on binary search tree. My code runs perfectly on linux ecosystems like Ubuntu or WSL2 but gives incorrect output in windows ecosystem more specifically Windows 10. Here's my code
#include <stdio.h>
#include <malloc.h>
typedef struct TreeNode
{
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct node
{
TreeNode *data;
struct node *next;
} node;
typedef struct queue
{
node *head;
node *tail;
int size;
} queue;
TreeNode *insert_in_bst(int element, TreeNode *root);
TreeNode *delete_in_bst(int element, TreeNode *root);
void inorder(TreeNode *root);
void levelwise(TreeNode *root);
void enqueue(queue *q, TreeNode *root);
node *dequeue(queue *q);
void mirror_image(TreeNode *root);
int height(TreeNode *root);
int main(int argc, char *argv[])
{
int n = 0;
printf("Enter elements to be added to bst - ");
scanf("%d", &n);
TreeNode *root;
while (n != -1)
{
root = insert_in_bst(n, root);
scanf("%d", &n);
}
levelwise(root);
printf("\nCurrent inorder - ");
inorder(root);
int del;
printf("\nEnter element to delete - ");
scanf("%d", &del);
delete_in_bst(del, root);
levelwise(root);
printf("\nNew inorder - ");
inorder(root);
printf("\nMirror image\n");
mirror_image(root);
levelwise(root);
int h = height(root);
printf("\nHeight = %d", h);
return 0;
}
TreeNode *insert_in_bst(int element, TreeNode *root)
{
if (!root)
{
TreeNode *newNode = (TreeNode *)malloc(sizeof(TreeNode));
newNode->data = element;
return newNode;
}
if (element < root->data)
{
root->left = insert_in_bst(element, root->left);
}
else
{
root->right = insert_in_bst(element, root->right);
}
return root;
}
TreeNode *delete_in_bst(int element, TreeNode *root)
{
if (!root)
return NULL;
if (element < root->data)
{
root->left = delete_in_bst(element, root->left);
}
else if (element > root->data)
{
root->right = delete_in_bst(element, root->right);
}
else
{
if (!root->left)
return root->right;
else if (!root->right)
return root->left;
else
{
TreeNode *curr = root->right;
while (!curr->left)
curr = curr->left;
root->data = curr->data;
root->right = delete_in_bst(curr->data, root->right);
}
}
return root;
}
void inorder(TreeNode *root)
{
if (!root)
return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
void levelwise(TreeNode *root)
{
node *currNode = (node *)malloc(sizeof(node));
currNode->data = root;
queue *q = (queue *)malloc(sizeof(queue));
enqueue(q, root);
while (q->size != 0)
{
int l = q->size;
for (int i = 0; i < l; i++)
{
node *temp = dequeue(q);
TreeNode *t = temp->data;
printf("%d ", t->data);
if (t->left)
{
enqueue(q, t->left);
}
if (t->right)
{
enqueue(q, t->right);
}
}
printf("\n");
}
}
void enqueue(queue *q, TreeNode *root)
{
node *temp = (node *)malloc(sizeof(node));
temp->data = root;
if (!q || !q->head)
{
q->head = temp;
q->tail = temp;
q->size = 1;
}
else
{
q->tail->next = temp;
q->tail = q->tail->next;
q->size++;
}
}
node *dequeue(queue *q)
{
node *top = q->head;
q->head = q->head->next;
q->size--;
return top;
}
void mirror_image(TreeNode *root)
{
if (!root)
return;
TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
mirror_image(root->left);
mirror_image(root->right);
}
int height(TreeNode *root)
{
if (!root)
return 0;
int lh = height(root->left);
int rh = height(root->right);
return 1 + (lh > rh ? lh : rh);
}
Heres the output on Windows ecosystems
Here's the output on linux/wsl2
On further debugging on Windows systems, i found out that by default; value to root is assigned as 1. On linux systems this thing doesnt happen. Can someoe help me find out the reason?
Thank you!

Why am I not getting the last print statement, unable to get height of the tree?

After taking values for nodes, program terminates. I don't know what I am doing wrong. I don't even know if the values are getting inserted.
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* GetNode(int data){
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->data=data;
newnode->left = NULL;
newnode->right = NULL;
}
struct Node* insert(struct Node* root,int data){
if(root=NULL){
root = GetNode(data);
return root;
}
else if(data <= root->data){
root->left = insert(root->left,data);
}
else{
root->right = insert(root->right,data);
}
return root;
}
int height(struct Node* root){
if(root==NULL){
return 0;
}
else{
int lh = height(root->left);
int rh = height(root->right);
if(lh>rh){
return (lh+1);
}
else{
return (rh+1);
}
}
}
int main() {
struct Node* root =NULL;
int n,i;
printf("Enter the total number of nodes in the tree: ");
scanf("%d",&n);
int value[n];
for(i=0;i<n;i++){
printf("Enter the %d node ",i+1);
scanf("%d",&value[i]);
}
for(i=0;i<n;i++){
root = insert(root,value[i]);
}
int high = height(root);
printf("Height of the given tree is : %d ",high);
return 0;
}
No, idea if it is the height function or the insert function.
You have 2 problems in your code.
In the function struct Node* GetNode(int data), you are not returning the newnode.
In the function struct Node* insert(struct Node* root,int data), in the if condition if(root=NULL), you should use ==
Here is the corrected working code:
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* GetNode(int data){
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->data=data;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
struct Node* insert(struct Node* root,int data){
if(root==NULL){
root = GetNode(data);
return root;
}
else if(data <= root->data){
root->left = insert(root->left,data);
}
else{
root->right = insert(root->right,data);
}
return root;
}
int height(struct Node* root){
if(root==NULL){
return 0;
}
else{
int lh = height(root->left);
int rh = height(root->right);
if(lh>rh){
return (lh+1);
}
else{
return (rh+1);
}
}
}
int main() {
struct Node* root =NULL;
int n,i;
printf("Enter the total number of nodes in the tree: ");
scanf("%d",&n);
int value[n];
for(i=0;i<n;i++){
printf("Enter the %d node ",i+1);
scanf("%d",&value[i]);
}
for(i=0;i<n;i++){
root = insert(root, value[i]);
}
int high = height(root);
printf("Height of the given tree is : %d ",high);
return 0;
}

Display function in Circular Linked List in C

I am having a problem with my Circular Linked list. I believe the problem is with my display function. Please let me know what is going wrong. The problem I have is that the first n-1 elements are displayed and then I get a segmentation fault(The last element doesn't get displayed and I get a segmentation fault).Thank you :-)
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* link;
};
struct Node* last = NULL;
void Insert_begin(int a)
{
struct Node* temp;
temp = malloc(sizeof(struct Node));
temp->data = a;
if (last == NULL)
last = temp;
else
{
temp->link = last->link;
last->link = temp;
}
}
void Display()
{
struct Node* temp;
if (last == NULL)
{
printf("list is empty");
}
temp = last->link;
while(temp!=last)
{
printf("%d\n",temp->data);
temp = temp->link;
}
printf("%d\n",temp->data);
}
int main()
{
Insert_begin(0);
Insert_begin(1);
Insert_begin(2);
Insert_begin(3);
Insert_begin(4);
Display();
return 0;
}
When you insert the first element into the list, you must its link point to itself:
if (last == NULL) {
last = temp;
last->link = last;
} else ...
In your code, the link from the last element was uninitialised.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* link;
};
struct Node* last = NULL;
void Insert_begin(int a)
{
struct Node* temp;
temp = malloc(sizeof(struct Node));
temp->data = a;
if (last == NULL)
{
last = temp;
temp->link=last;//you forget this
}
else
{
temp->link = last->link;
last->link = temp;
last=temp;
}
}
void Display()
{
struct Node* temp;
if (last == NULL)
{
printf("list is empty");
return;
}
temp = last->link;
while(temp!=last)
{
printf("%d\n",temp->data);
temp = temp->link;
}
printf("%d\n",temp->data);
}
int main()
{
Insert_begin(0);
Insert_begin(1);
Insert_begin(2);
Insert_begin(3);
Insert_begin(4);
Display();
return 0;
}
if (last == NULL)
{
last = temp;
**// adding this line
last->link = last;**
}
That solve the problem
Below is corrected code:
one mistake you have done that is at inserting first value you are not pointing the link to first node itself.In circular singly linked list if there is one node then link(next in general) field should be pointed to that node itself.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* link;
};
struct Node* last = NULL;
void Insert_begin(int a)
{
struct Node* temp;
temp = malloc(sizeof(struct Node));
temp->data = a;
if (last == NULL)
{
last = temp;
/*link field is pointing to that node
*it self(you have forgotten this)*/
last->link = temp;
}
else
{
temp->link = last->link;
last->link = temp;
}
}
void Display()
{
struct Node* temp;
if (last == NULL)
{
printf("list is empty");
}
temp = last->link;
while(temp!=last)
{
printf("%d\n",temp->data);
temp = temp->link;
}
printf("%d\n",temp->data);
}
int main()
{
Insert_begin(0);
Insert_begin(1);
Insert_begin(2);
Insert_begin(3);
Insert_begin(4);
Display();
return 0;
}
*
Problem is with Insert_begin(int a) function,
When you are inserting first node, you are not linking his next to itself, so next time while inserting second/third/.. node, you trying to access first node as last->link but it gives you garbage value and that is reason
void Insert_begin(int a)
{
struct Node* temp;
temp = malloc(sizeof(struct Node));
temp->data = a;
if (last == NULL)
{
last = temp;
last->link = last;
}
else
{
temp->link = last->link;
last->link = temp;
last = temp;
}
}
void Display()
{
struct Node* temp;
if (last == NULL)
{
printf("list is empty");
}
else
{
temp = last->link;
while(temp!=last);
{
printf("%d\n",temp->data);
temp = temp->link;
}
printf("%d\n",temp->data);
}
}
void main()
{
Insert_begin(10);
Insert_begin(20);
Insert_begin(30);
Display();
}

segmenation fault error in my linkedList -C

I put together a few pieces of code to make a linked list that adds to head(Has a special function) and in the middle(also special function).
my problem is, i need to provide the program with numbers and insert them as nodes in my LINKEDLIST. However, my display function(to display the tree of nodes) gives back segmentation fault and so does just taking values in without any display function.
I'm fairly new to malloc so i suspect the problem is there?
Thanks
#include<stdio.h>
#include<stdlib.h>
/*LINKEDLIST STRUCT*/
struct node {
int data;
struct node *next;
};
/*Inserting head-Node*/
struct node *insert_head(struct node *head, int number)
{
struct node *temp;
temp = malloc(sizeof(struct node));
if(temp == NULL)
{
printf("Not enough memory\n");
exit(1);
}
temp->data = number;
temp->next = head;
head = temp;
return head;
}
/*Inserting inside a list*/
void after_me(struct node *me, int number)
{
struct node *temp;
temp = malloc(sizeof(struct node));
if(temp == NULL)
{
printf("Not enough memory\n");
exit(1);
}
temp->data = number;
temp->next = me->next;
me->next = temp;
}
/*PRINTING LIST*/
void display(struct node *head)
{
struct node *moving_ptr = head;
while(moving_ptr != NULL)
{
printf("%d-->",moving_ptr->data);
moving_ptr = moving_ptr->next;
}
}
int main()
{
int index;
struct node *head;
struct node *previous_node;
scanf("%d", &index);
while(index > 0)
{
/*allocating in List */
if(head == NULL)
head = insert_head(head,index);
else
if((head != NULL) && (index <= (head->data)))
{
struct node *temp;
head->next = temp;
temp->next = head;/*TRY INSERT HEAD FUNC.*/
}
else
if((head != NULL) && (index > (head->data)))
{
previous_node->data = index-1;
after_me(previous_node,index);
}
scanf("%d", &index);
}
display(head);
}
I suggest as follows.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
//aggregated into one place
struct node *new_node(int number){
struct node *temp;
if(NULL == (temp = malloc(sizeof(*temp)))){
printf("\nNot enough memory\n");
exit(1);
}
temp->data = number;
temp->next = NULL;
return temp;
}
struct node *insert_head(struct node *head, int number) {
struct node *temp = new_node(number);
temp->next = head;
return temp;
}
void after_me(struct node *me, int number){
struct node *temp = new_node(number);
temp->next = me->next;
me->next = temp;
}
void display(struct node *head){
struct node *moving_ptr = head;
while(moving_ptr != NULL){
printf("%d", moving_ptr->data);
if(moving_ptr = moving_ptr->next)
printf("-->");
}
putchar('\n');
}
struct node *insert(struct node *me, int number){
if(me){
if(number <= me->data){
me = insert_head(me, number);
} else {
me->next = insert(me->next, number);
}
} else {
me = new_node(number);
}
return me;
}
void release(struct node *list){//Of course, you will be able to replace a simple loop(e.g while-loop).
if(list){
release(list->next);
free(list);
}
}
int main(void){
struct node *head = NULL;
int index;
while(1==scanf("%d", &index) && index > 0){
head = insert(head, index);
}
display(head);
release(head);
return 0;
}

Linked list (sorted insertion)

this program creates a sorted list and then inserts an element such that the list still remains sorted. I think the logic is ok..but the program doesn't print the new list formed.Here is the code. what is wrong?
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct list {
int number;
struct list *next;
};
typedef struct list node;
void create(node *);
void print(node *);
void sortedInsert(node **);
main() {
int user_response;
node *head;
head = (node *)malloc(sizeof(node));
create(head);
printf("Look at your creation!! A linked list!!1 heheheh...........\n");
print(head);
printf("Do you want to experience some \"sort\" of thrill?\n1 for yes..\n");
scanf("%d",&user_response);
if(user_response == 1) {
sortedInsert(&head);
printf("Look at the marvel of linked list...\n");
print(head);
}
else {
printf("Ha\n tired fellow,lack of ambition!!!\n");
exit(0);
}
return 0;
}
void create(node *head) {
printf("Enter a number,-999 to stop\n");
scanf("%d",&head->number);
if(head->number == -999) {
head->next = NULL;
}
else {
head->next = (node *)malloc(sizeof(node));
create(head->next);
}
}
void print(node *head) {
if(head->next != NULL) {
printf("%d-->",head->number);
print(head->next);
}
else {
printf("%d",head->number);
}
}
void sortedInsert(node **headRef) {
node *new_node;
node *prev_ptr = *headRef;
node *dummy_ptr = *headRef;
int key;
printf("Which value do you wanna insert\n");
scanf("%d",&key);
new_node = (node *)malloc(sizeof(node));
new_node->number = key;
while((*headRef)->next != NULL) {
if((*headRef)->number >= key) {
prev_ptr->next = new_node;
new_node->next = *headRef;
*headRef = dummy_ptr;
}
else {
prev_ptr = *headRef;
*headRef = (*headRef)->next;
}
}

Resources