why the traversing part of my code isn't working? - data-structures

the creating of linked list is successful but retrieving data from nodes i.e; not giving an expected output. the traversing part does not traverse all the data elements instead it is giving the output of only one data element infinite times. when i run the program it takes all the data elements but the traversing part i.e;( displaying the entire list) is not giving the expected output
`/**
* C program to create and traverse a Linked List
*/
#include <stdio.h>
#include <stdlib.h>
/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
}*head;
/*
* Functions to create and display list
*/
void createList(int n);
void traverseList();
int main()
{
int n;
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);
printf("\nData in the list \n");
traverseList();
return 0;
}
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;
head = (struct node *)malloc(sizeof(struct node));
// Terminate if memory not allocated
if(head == NULL)
{
printf("Unable to allocate memory.");
exit(0);
}
// Input data of node from the user
printf("Enter the data of node 1: ");
scanf("%d", &data);
head->data = data; // Link data field with data
head->next = NULL; // Link address field to NULL
// Create n - 1 nodes and add to list
temp = head;
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
/* If memory is not allocated for newNode */
if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
printf("Enter the data of node %d: ", i);
scanf("%d", &data);
newNode->data = data; // Link data field of newNode
newNode->next = NULL; // Make sure new node points to NULL
temp->next = newNode; // Link previous node with newNode
temp = temp->next; // Make current node as previous node
}
}
/*
* Display entire list
*/
void traverseList()
{
struct node *temp;
// Return if list is empty
if(head == NULL)
{
printf("List is empty.");
return;
}
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
} `
the expected output should be
Enter the total number of nodes: 5
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
Enter the data of node 5: 50
Data in the list
Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

I think you should use else condition after if
that is
include while(temp!=null) and code after that in else condition and check
void display()
{
struct node *ptr;
ptr=head;
if(head==NULL)
printf("null");
else
{
while(ptr!=NULL)
{
printf("%d->",ptr->data);
ptr=ptr->next;
}
}
}

Related

Inaccuracy in output of deletion function in binary search tree

I am making a binary search tree code, in that 'am facing an issue in the deletion function. After executing the function, the code is showing inorder display incorrectly. Basically, it is incorrect, and I'am not able to understand where the problem is.
In the delete function, I have used a search function that will find the node which the user has to delete. And I have used inorder successor method for deletion so the minimum function will find the successor. All other functions like insertion, minimum, and inorder are working fine.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
} node;
struct node *insert(struct node *tnode, int data)
{
if (tnode == NULL)
{
struct node *ptr;
ptr = (struct node *)malloc(sizeof(struct node));
ptr->data = data;
ptr->left = NULL;
ptr->right = NULL;
return ptr;
}
if (data > (tnode->data))
{
tnode->right = insert(tnode->right, data);
return tnode;
}
if (data < (tnode->data))
{
tnode->left = insert(tnode->left, data);
return tnode;
}
}
void in_order(struct node *tnode)
{
if (tnode == NULL)
return;
else
{
in_order(tnode->left);
printf("%d\t", tnode->data);
in_order(tnode->right);
}
}
struct node *search(struct node *tnode, int data)
{
if (tnode == NULL)
{
return NULL;
}
else
{
if (data == tnode->data)
{
return tnode;
}
else
{
if (data > tnode->data)
{
search(tnode->right, data);
}
else
{
search(tnode->left, data);
}
}
}
}
struct node *minimum(struct node *tnode)
{
if (tnode == NULL)
{
printf("No node present\n");
return NULL;
}
else
{
if (tnode->left == NULL)
return tnode;
else
minimum(tnode->left);
}
}
struct node *deletenode(struct node *tnode, int data)
{
struct node *s;
s = search(tnode, data);
if (s == NULL)
{
printf("Value not found\n");
return NULL;
}
else
{
if (s->left == NULL && s->right == NULL) // No child case
{
free(s);
return NULL;
}
else
{
if (s->left == NULL && s->right != NULL) // single child case(right child)
{
struct node *temp = s->right;
free(s);
return temp;
}
else if (s->right == NULL && s->left != NULL) // single child case(left child)
{
struct node *temp = s->left;
free(s);
return temp;
}
else
{
struct node *temp;
temp = minimum(s->right);
s->data = temp->data;
s->right = deletenode(s->right, temp->data);
}
}
}
return s;
}
int main()
{
struct node *root = NULL, *del;
int n, i, data, key;
printf("Enter how many nodes you have to enter in a tree\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter data\n");
scanf("%d", &data);
root = insert(root, data);
}
printf("\nIN-Order display\n");
in_order(root);
int d;
printf("\nEnter data to be delete\n");
scanf("%d", &d);
del=deletenode(root, d);
printf("\nIN-Order display\n");
in_order(root);
return 0;
}
There are several places missing return (in minimum, search and deletenode). You can easily find them if you compile with -Wall -Wextra compiler options.
It is not clear, what do you want to return from deletenode. I assume that it is a tree with deleted element. Then either search should return a parent node (so it is possible to change pointers to freed node), or deletenode should move to parent node.
Also, use in_order(del) instead of in_order(root) because root can be changed while deleting.

Segmentation Default

Creation of node:
struct Node
{
int data;
struct Node *link;
};
struct Node *head = NULL;
Append Function
int append()
{
struct Node *temp;
struct Node *p;
temp = (struct Node *)malloc(sizeof(struct Node));
printf("Enter the data");
scanf("%d", &temp->data);
if (head == NULL)
{ temp->link = NULL;
head = temp;
}
else
{
p = head;
while (p != NULL)
{
p = p->link;
}
p->link=NULL;
}
return p->data;
}
Main Function
void main()
{
int append();
int insert();
int insert_begin();
int display();
int delete ();
int del_between();
int k = 1, ch ,d;
while (k)
{
printf("\nEnter choice\n");
printf("1.Append\n");
printf("2.In between\n");
printf("3.At the beginning\n");
printf("4.Display\n");
printf("5.Delete\n");
printf("6.Delete from between\n");
printf("7.Quit\n");
scanf("%d", &ch);
switch (ch)
{
case 1:
d = append();
printf("pushed %d",d);
break;
case 2:
insert();
break;
case 3:
insert_begin();
break;
case 4:
display();
break;
case 5:
delete ();
break;
case 6:
del_between();
break;
case 7:
k = 0;
break;
default:
printf("wrong choice");
}
}
}
I have been trying to append a node at the end of a linked list but as soon as I enter the data to be added Segmentation default error occurs.
Output screen
Enter choice
1.Append
2.In between
3.At the beginning
4.Display
5.Delete
6.Delete from between
7.Quit
1
Enter the data23
Segmentation fault
.........................................................................................................
What is the meaning of Segmentation fault ?How to get rid of it? Where am I going wrong?
................................................................................................................
Thanks.
Segmentation fault occurs when you try to access some memory which is restricted.
The error came because in your case linked list is empty and first time when you call append function it goes to your if statement, and in your if head = temp; so you are updating your head with temp data. Further when the if condition ends you are returning the value of p return p->data; but this wont work.
As p is only initialized but with no data value thus accessing something which is not assigned giving SIGSEGV.
you can resolve the error by editing :
if (head == NULL)
{ temp->link = NULL;
head = temp;
return head->data;
}
else
{
p = head;
while (p != NULL)
{
p = p->link;
}
p->link=temp;
p=temp;
temp->link=NULL;
}
return p->data;

Why is this implementation for checking balanced binary tree wrong

public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int rightCount = maxDepth(root.right);
int leftCount = maxDepth(root.left);
if(Math.abs(rightCount-leftCount)<=1) return true;
return false;
}
public int maxDepth(TreeNode root){
if(root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
Checking the max depth for both branches and determining if the absolute value is <=1
At first:
If you have invalid root arg isBalanced returns true, so that is bad implementation, despite the fact that code could have no errors.
In my opinion, function should work with valid arguments, otherwise throw exception (error?).
Also check this solution, read code and try to do something like this:
/* C program to check if a tree is height-balanced or not */
#include <stdio.h>
#include <stdlib.h>
#define bool int
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node {
int data;
struct node* left;
struct node* right;
};
/* Returns the height of a binary tree */
int height(struct node* node);
/* Returns true if binary tree with root as root is height-balanced */
bool isBalanced(struct node* root)
{
int lh; /* for height of left subtree */
int rh; /* for height of right subtree */
/* If tree is empty then return true */
if (root == NULL)
return 1;
/* Get the height of left and right sub trees */
lh = height(root->left);
rh = height(root->right);
if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right))
return 1;
/* If we reach here then tree is not height-balanced */
return 0;
}
/* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */
/* returns maximum of two integers */
int max(int a, int b)
{
return (a >= b) ? a : b;
}
/* The function Compute the "height" of a tree. Height is the
number of nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
/* base case tree is empty */
if (node == NULL)
return 0;
/* If tree is not empty then height = 1 + max of left
height and right heights */
return 1 + max(height(node->left), height(node->right));
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
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 main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->left->left = newNode(8);
if (isBalanced(root))
printf("Tree is balanced");
else
printf("Tree is not balanced");
getchar();
return 0;
}
(copy & pasted from here)

I need to design an algorithm to return the number of nodes in a binary tree that have two children

I have come across this question to design an algorithm to count the number of nodes in a binary tree that has two children. It was mentioned that the solution should be expressed as a pair of functions(not BST member functions).
So far I could not arrive at a concrete solution and specially the part where the solution should be expressed as a pair of non BST member functions is going over my head.
//count the number of node that has got 2 children
function countNodes(nodeElement,nodeNumber){
var nodeNumber = 0;
var children = nodeElement.children;
for(var c=0;c<children ;c++){
//check if current node has got two childs
if(getNodeChildren(children[c])==2){
nodeNumber++;
}
//recursively check if children nodes has got 2 children
nodeNumber += countNodes(children[c],nodeNumber)
}
return nodeNumber;
}
//recursively counts the number of children that a node has got
function getNodeChildren(nodeElement){
//check if is a leaf
if(nodeElement.children == 0){
return 1;
}
else {
var nodeNumber = 0;
var children = nodeElement.children;
for(var c=0;c<children ;c++){
nodeNumber += getNodeChildren(children[c],nodeNumber+1);
}
return nodeNumber;
}
}
Assuming Node is a struct containing two pointers to Node, named left and right:
int count_2_ch_nodes(Node* root)
{
if (root == NULL) return 0;
// Recursively count the number of nodes that are below
// this node that have two children:
int count = 0;
if (root->left != NULL) count += count_2_ch_nodes(root->left);
if (root->right != NULL) count += count_2_ch_nodes(root->right);
// Add this node IF it has 2 children:
if (has_2_ch(root)) count++;
return count;
}
/* Returns TRUE if node has two children */
int has_2_ch(Node* node)
{
return (node->left != NULL && node->right != NULL);
}
This is the complete java code for your question.
import java.util.ArrayList;
import java.util.Scanner;
/*
* Creating datastructure for Node
* Every Node contains data given by user and leftChild and rightChild childs
* Left and rightChild childs are automatically assigned by the program
*/
class Node
{
Node leftChild, rightChild;
String data;
/*
* Assigning leftChild , rightChild and data to the node using a constructor
*/
Node(Node left, Node right, String data)
{
this.leftChild =left;
this.rightChild =right;
this.data=data;
}
}
public class FirstAnswer {
/*
* Initializing the count for number of nodes
*/
private static int count=0;
private static int numberOfNodes(Node root)
{
/*
* Writing the base case for the recursive function
* If leftChild or rightChild or both are null it returns 0 as no childs are present
*/
if ((root.leftChild ==null && root.rightChild ==null) || (root.leftChild ==null) || (root.rightChild ==null))
return 0;
else {
count+=2;
Node left=root.leftChild;
Node right=root.rightChild;
/*
* Calling the recursive function twice by making leftChild child and rightChild child of root as root
*/
System.out.println(root.data+" : "+"\n"+"Left child : "+left.data+"\n"+"Right child : "+right.data);
numberOfNodes(left);
numberOfNodes(right);
}
return count+1; //Since root node is not counted
}
public static void main(String... args)
{
Scanner sc=new Scanner(System.in);
/*
* Creating individual nodes with string data from user
* Holding them in an array list inputs
*/
ArrayList<Node> inputs=new ArrayList<>();
String status="Y";
System.out.print("Enter data for root node : ");
inputs.add(new Node(null,null,sc.next()));
while (status.equals("Y") || status.equals("y"))
{
if (inputs.size()%2==1)
{
for (int j=0;j<2;j++)
{
System.out.print("data for child "+(j+1)+" : ");
inputs.add(new Node(null,null,sc.next()));
}
/*
* Yes or No for adding more number of nodes
*/
System.out.println("Press Y or y if more inputs have to be given else press N to construct tree with given inputs...");
status=sc.next();
}
}
Node[] tree=new Node[inputs.size()];
/*
* Above is the tree which is being constructed from the nodes given by user
*/
for (int i=inputs.size()-1;i>=0;i--)
{
int j=i+1;
/*
* Making tree format by locating childs with indices at 2*p and 2*p+1
*/
if ((2*j+1)<=inputs.size())
{
tree[i]=new Node(tree[2*i+1],tree[2*i+2],inputs.get(i).data);
}
else {
tree[i]=inputs.get(i);
}
}
/*
* Calling the recursive function to count number of nodes
* Since first node is the root we start from here
*/
System.out.println(numberOfNodes(tree[0]));
}
}
Hope this helps you ;)

AVL Tree. Print element by position (when sorted)

#include<stdio.h>
#include<stdlib.h>
// An AVL tree node
struct node
{
int key;
struct node *left;
struct node *right;
int height;
};
// A utility function to get maximum of two integers
int max(int a, int b);
// A utility function to get height of the tree
int height(struct node *N)
{
if (N == NULL)
return 0;
return N->height;
}
// A utility function to get maximum of two integers
int max(int a, int b)
{
return (a > b)? a : b;
}
/* Helper function that allocates a new node with the given key and
NULL left and right pointers. */
struct node* newNode(int key)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return(node);
}
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
struct node *rightRotate(struct node *y)
{
struct node *x = y->left;
struct node *T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct node *leftRotate(struct node *x)
{
struct node *y = x->right;
struct node *T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left), height(x->right))+1;
y->height = max(height(y->left), height(y->right))+1;
// Return new root
return y;
}
// Get Balance factor of node N
int getBalance(struct node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
struct node* insert(struct node* node, int key)
{
/* 1. Perform the normal BST rotation */
if (node == NULL)
return(newNode(key));
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
/* 2. Update height of this ancestor node */
node->height = max(height(node->left), height(node->right)) + 1;
/* 3. Get the balance factor of this ancestor node to check whether
this node became unbalanced */
int balance = getBalance(node);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && key < node->left->key)
return rightRotate(node);
// Right Right Case
if (balance < -1 && key > node->right->key)
return leftRotate(node);
// Left Right Case
if (balance > 1 && key > node->left->key)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node->right->key)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
/* return the (unchanged) node pointer */
return node;
}
/* Given a non-empty binary search tree, return the node with minimum
key value found in that tree. Note that the entire tree does not
need to be searched. */
struct node * minValueNode(struct node* node)
{
struct node* current = node;
/* loop down to find the leftmost leaf */
while (current->left != NULL)
current = current->left;
return current;
}
struct node* deleteNode(struct node* root, int key)
{
// STEP 1: PERFORM STANDARD BST DELETE
if (root == NULL)
return root;
// If the key to be deleted is smaller than the root's key,
// then it lies in left subtree
if ( key < root->key )
root->left = deleteNode(root->left, key);
// If the key to be deleted is greater than the root's key,
// then it lies in right subtree
else if( key > root->key )
root->right = deleteNode(root->right, key);
// if key is same as root's key, then This is the node
// to be deleted
else
{
// node with only one child or no child
if( (root->left == NULL) || (root->right == NULL) )
{
struct node *temp = root->left ? root->left : root->right;
// No child case
if(temp == NULL)
{
temp = root;
root = NULL;
}
else // One child case
*root = *temp; // Copy the contents of the non-empty child
free(temp);
}
else
{
// node with two children: Get the inorder successor (smallest
// in the right subtree)
struct node* temp = minValueNode(root->right);
// Copy the inorder successor's data to this node
root->key = temp->key;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
}
// If the tree had only one node then return
if (root == NULL)
return root;
// STEP 2: UPDATE HEIGHT OF THE CURRENT NODE
root->height = max(height(root->left), height(root->right)) + 1;
// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether
// this node became unbalanced)
int balance = getBalance(root);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
// Left Right Case
if (balance > 1 && getBalance(root->left) < 0)
{
root->left = leftRotate(root->left);
return rightRotate(root);
}
// Right Right Case
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
// Right Left Case
if (balance < -1 && getBalance(root->right) > 0)
{
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
// A utility function to print preorder traversal of the tree.
// The function also prints height of every node
void preOrder(struct node *root)
{
if(root != NULL)
{
preOrder(root->left);
printf("%d ", root->key);
preOrder(root->right);
}
}
/* Drier program to test above function*/
int main()
{
struct node *root = NULL;
/* Constructing tree given in the above figure */
root = insert(root, 9);
root = insert(root, 5);
root = insert(root, 10);
root = insert(root, 0);
root = insert(root, 6);
root = insert(root, 11);
root = insert(root, -1);
root = insert(root, 1);
root = insert(root, 2);
root = insert(root, 10);
printf("Pre order traversal of the constructed AVL tree is \n");
preOrder(root);
root = deleteNode(root, 10);
printf("\nPre order traversal after deletion of 10 \n");
preOrder(root);
return 0;
}
How can i print an element when I give a certain position?
example:
root = insert(root, 100); (add 100)
root = insert(root, 300); (add 300)
root = insert(root, 200); (add 200)
root = insert(root, 200); (add 400)
PRINT 1 -> Should print the first element (sorted). Which is 100
PRINT 3 -> Should print the third element (sorted). Which is 300
How can I implement this PRINT on my AVL Tree?
I tried to modify this function but i did not succeed
void preOrder(struct node *root)
{
if(root != NULL)
{
preOrder(root->left);
printf("%d ", root->key);
preOrder(root->right);
}
}
I couldn't use a if statment here to check what values are passing because they are all passed at the same time.
preOrder function will order the numbers. lower to biggest.
I don't understand why you can't modify preOrder to do that - you just have to "remember" that current position an update it along the way:
int findPositionPreOrder(
struct node *root,
int targetPos,
int curPos)
{
if(root != NULL)
{
int newPos = findPositionPreOrder(root->left, targetPos, curPos);
newPos++;
if (newPos == targetPos)
{
printf("%d\n", root->key);
}
return findPositionPreOrder(root->right, targetPos, newPos);
}
else
{
return curPos;
}
}
And you call it like findPositionPreOrder(root, targetPosition, 0);
This is not an optimal solution - you can break the recursion after finding your desired position instead of traversing the rest of the tree.

Resources