I want to write a BST,but the insert function doesn't work. Debugging it , I found that it was not inserting.
/* Binary Search Tree (BST).demo */
#include <stdio.h>
#include <stdlib.h>
typedef struct treeNode{
int data;
struct treeNode* lChild;
struct treeNode* rChild;
} treeNode;
treeNode* createNode(){
treeNode *nNode;
nNode=(struct treeNode*)malloc(sizeof(treeNode));
nNode->data=0;
nNode->lChild=NULL;
nNode->rChild=NULL;
return nNode;
}
void insert(treeNode* rt,int idata)
{
if(rt==NULL){
treeNode* nNode;
nNode=createNode();
nNode->data=idata;
rt=nNode;
rt->lChild=NULL;
rt->rChild=NULL;
}else{
if(idata < rt->data)
insert(rt->lChild,idata);
else insert(rt->rChild,idata);
}
}
int main()
{
treeNode *root;
root=(treeNode*)malloc(sizeof(treeNode));
root->data=15;
root->lChild=NULL;
root->rChild=NULL;
insert(root,13);
if(root->lChild==NULL)
printf("root no l child\n");
// printf("root lchild data :%d",root->lChild->data);
return 0;
}
use this as the insert function :
void insert(treeNode** rt,int idata)
{
if((*rt)==NULL)
{
treeNode* nNode;
nNode=createNode();
nNode->data=idata;
*rt=nNode;
(*rt)->lChild=NULL;
(*rt)->rChild=NULL;
}
else
{
if(idata < (*rt)->data)
insert(&((*rt)->lChild),idata);
else
insert(&((*rt)->rChild),idata);
}
}
and the insert function call in main() as:
insert(&root,13);
I usually implement it like this:
void insert(treeNode* rt, int idata) {
// assert( rt != NULL );
if(idata < rt->data){
if( rt->lChild != NULL)
insert(rt->lChild, idata);
else {
rt->lChild = createNode();
rt->lChild->data = idata;
}
} else {
if( rt->rChild != NULL)
insert(rt->rChild, idata);
else {
rt->rChild = createNode();
rt->rChild->data = idata;
}
}
}
Moreover, I prefer give an argument to createNode()
treeNode* createNode(int idata){
// ...
nNode->data = idata;
// ...
}
So the insert will look like:
void insert(treeNode* rt, int idata) {
// ...
rt->lChild = createNode(idata);
// ...
rt->rChild = createNode(idata);
// ...
}
Related
Below is the program
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
struct node* reverse_ll(struct node* hnode)
{
if(hnode == 0)
{
return 0;
}
if(hnode->next == 0)
{
head=hnode;
return hnode;
}
struct node* ptr=reverse_ll(hnode->next);
ptr->next=hnode;
hnode->next=0;
//return hnode;
}
void display()
{
struct node *ptr;
ptr=head;
if(ptr==0)
{
printf("empty");
}
else
{
while(ptr!=0)
{
printf("%d->",ptr->data);
ptr=ptr->next;
}
printf("null");
}
}
int main()
{
struct node* h;
lastinsert(1);
lastinsert(2);
lastinsert(3);
lastinsert(4);
lastinsert(5);
display();
h=reverse_ll(head);
display();
return 0;
}
In function reverse_ll() even if I comment "return hnode" I am getting the right output How is it possible where does ptr receives its address from when I comment "return hnode"?
output: 1->2->3->4->5->null
5->4->3->2->1->null
reverse_ll() must return a struct node * in the recursive case:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head;
void lastinsert(int data) {
struct node **c = &head;
for(; *c; c = &(*c)->next);
*c = malloc(sizeof(*head));
if (!(*c)) {
printf("malloc failed\n");
return;
}
(*c)->data = data;
(*c)->next = NULL;
}
struct node *reverse_ll(struct node* hnode) {
if(!hnode)
return NULL;
if(!hnode->next) {
head = hnode;
return hnode;
}
struct node *ptr=reverse_ll(hnode->next);
ptr->next=hnode;
hnode->next = NULL;
return hnode;
}
void display() {
if(!head) {
printf("empty");
return;
}
for(struct node *ptr = head; ptr; ptr = ptr->next) {
printf("%d->",ptr->data);
}
printf("null\n");
}
int main() {
for(int i = 1; i <= 5; i++) {
lastinsert(i);
}
display();
reverse_ll(head);
display();
// It's good practice to implement a function that frees you list
// which you would call here.
return 0;
}
and example run:
$ ./a.out
1->2->3->4->5->null
5->4->3->2->1->null
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
I am learning the C language and trying to build a C binary tree library. My structure is defined as:
struct Node {
int value;
struct Node *left;
struct Node *right;
};
typedef struct Node TNode;
typedef struct Node *binary_tree;
It is created like this:
binary_tree NewBinaryTree(int value_root) {
binary_tree newRoot = malloc(sizeof(TNode));
if (newRoot) {
newRoot->value = value_root;
newRoot->left = NULL;
newRoot->right = NULL;
}
return newRoot;
}
I add elements to it like:
void Insert(binary_tree *tree, int val) {
if (*tree == NULL) {
*tree = (binary_tree)malloc(sizeof(TNode));
(*tree)->value = val;
(*tree)->left = NULL;
(*tree)->right = NULL;
} else {
if (val < (*tree)->value) {
Insert(&(*tree)->left, val);
} else {
Insert(&(*tree)->right, val);
}
}
}
This kinda "sort" the tree by checking the value.However I would like a function that simply add the val value to the left(left) without doing any sorting. I did:
void InsertLeft(binary_tree *tree, int val) {
Insert(&(*tree)->left, val);
}
I call the function like this:
InsertLeft(&tree, 8);
I have a main program that initialise the tree like this:
tree = NewBinaryTree(3);
Also a tree display method:
void display_binary_tree( binary_tree tree )
{
if( tree != NULL )
{
display_binary_tree( tree->left ) ;
printf( "%d " , tree->value ) ;
display_binary_tree( tree->right ) ;
}
}
and afterwards I can add elements by calling the Insert(binary_tree *tree, int val) function, however when calling this function, it just crashes the program. I dont understand why.
I was trying out the code for level order traversal in a binary search tree using a queue and I don't know why I'm getting no output when I try to print the level order. Someone please help!
Link to my code.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int data;
struct Node *right, *left;
}Node;
typedef struct
{
int front, rear, size;
unsigned capacity;
Node* arr[100];
}Queue;
Queue* createQ()
{
Queue* q = (Queue*) malloc(sizeof(Queue));
q->capacity = 100;
q->front = q->size = 0;
q->rear = q->capacity - 1;
return q;
}
int isEmpty(Queue* q)
{
return (q->size == 0);
}
int isFull(Queue* q)
{
return (q->size == q->capacity);
}
void enqueue(Queue* q, Node* item)
{
if (isFull(q))
return;
q->rear = (q->rear + 1)%q->capacity;
q->arr[q->rear] = item;
q->size = q->size + 1;
}
Node* dequeue(Queue* q)
{
if (isEmpty(q))
return NULL;
Node* item = q->arr[q->front];
q->front = (q->front + 1)%q->capacity;
q->size = q->size - 1;
return item;
}
Node* create(Node* root, int data)
{
if(root==NULL)
{
root = (Node*)malloc(sizeof(Node));
root->data = data;
root->left = root->right = NULL;
return root;
}
else
{
if(data>root->data)
{
root->right = create(root->right,data);
}
else
{
root->left = create(root->left,data);
}
return root;
}
}
void levelorder(Node* root)
{
if(root==NULL) return;
else
{
Queue* q = createQ();
enqueue(q,root);
while(isEmpty(q))
{
Node* temp = dequeue(q);
printf("%d ",temp->data);
if(temp->right)
enqueue(q,temp->right);
else if(temp->left);
enqueue(q,temp->left);
}
}
}
void main()
{
int data;
Node *root = NULL;
for(;;)
{
printf("\nEnter the elements (-1 to stop) : ");
scanf("%d",&data);
if(data==-1) break;
root = create(root,data);
}
printf("\nPrinting the elemtents in level order : ");
levelorder(root);
}
You have several bugs in your levelorder function. Please check the corrections below. I've kept your buggy line in side comment.
void levelorder(Node* root)
{
if(root==NULL) return;
else
{
Queue* q = createQ();
enqueue(q,root);
while(!isEmpty(q)) // not while(isEmpty(q)) you have to check untill Queue is non-empty
{
Node* temp = dequeue(q);
printf("%d ",temp->data);
if(temp->right)
enqueue(q,temp->right);
if(temp->left) // not else if(temp->left); there can be right node and left node as well.. no semicolon
enqueue(q,temp->left);
}
}
}
Rest of the code is okay. You should practice debugging yourself using some well-known IDE.
In line 83, while(isEmpty(q)) should be while(!isEmpty(q)) because we would want to run the loop while the Queue is non-empty.
I hope I got the bug right.
i have to create binary search tree. so i have used nested structure. i am not able to maintain head of the tree. when i give inputs then it is creating new node of every input. Help me with how to handle Head.
tree.h
#ifndef __TREE__H__
#define __TREE__H__
typedef struct _BSTNode
{
int data;
struct _BSTNode *left,*right;
}BSTNode;
typedef struct _BST
{
BSTNode *tHead;
}BST;
int insertBST(BST ,int);
#endif
mainTree.c
#include"tree.h"
#include<stdio.h>
int main()
{
FILE *fp;
BST bst;
bst.tHead=NULL;
int element;
fp = fopen("input","r");
while(fscanf(fp,"%d",&element)!=EOF)
{
insertBST(bst,element);
}
return 0;
}
insertBST.c
#include"tree.h"
#include<stdio.h>
int insertBST(BST bst,int element)
{
return _insertBST(bst.tHead,NULL,element);
}
int _insertBST(BSTNode *p,BSTNode *parent,int e)
{
if(p==NULL)
return createBST(p,e);
if(p->data == e)
return 0;
if(p->data < e)
return _insertBST(p->right,p,e);
if(p->data > e)
return _insertBST(p->left,p,e);
return -1;
}
createBST.c
#include"tree.h"
#include<stdlib.h>
#include<stdio.h>
int createBST(BSTNode *p,int element)
{
BSTNode *node = (BSTNode *)malloc(sizeof(BSTNode));
node->data = element;
node->left = NULL;
node->right = NULL;
if(p== NULL)
{
p=node;
fprintf(stdout,"Im here 1");
return 0;
}
else
{
if(p->data < node ->data)
(p->left) = node;
fprintf(stdout,"Im here 2");
return 0;
if(p->data > node ->data)
(p->right) = node;
fprintf(stdout,"Im here 3");
return 0;
}
}
output:-
#:~/Ds/tree$gcc mainTree.c insertBST.c createBST.c
#:~/Ds/tree$ ./a.out
Im here 1Im here 1Im here 1Im here 1Im here 1
input :- 40 10 30 20