Binary tree doesn't work the print - c

I'm implementing my own binary tree and this is my node structure:
struct node {
int value;
struct node *left;
struct node *right;
};
and my start node:
struct node * start = NULL;
this is my insert function:
void insert(int value, struct node *leaf) {
if (leaf == NULL) {
leaf = (struct node*) malloc( sizeof( struct node ) );
leaf->value = value;
leaf->left = NULL;
leaf->right = NULL;
} else if (value < leaf->value) {
insert(value, leaf->left);
} else if (value > leaf->value) {
insert(value, leaf->right);
}
}
and this is the function I use for visiting the tree:
void print_tree(struct node * leaf) {
if (leaf == NULL)
return;
print_tree(leaf->left);
printf(" %d ", leaf->value);
print_tree(leaf->right);
}
The problem is that after I insert all the values it prints nothing.

I'm assuming that you're calling the insert in this way:
insert(5, start);
The problem is that in this way you are copying NULL into the leaf local variable of the insert function.
So also if you are allocating memory for the nodes, you aren't updating the start pointer.
In order to do this you need to use a double pointer in your insert function (struct node ** leaf).
This should work:
void insert(int value, struct node **leaf)
{
if( (*leaf) == NULL )
{
(*leaf) = malloc( sizeof( struct node ) ); // You don't need casting
(*leaf)->value = value;
(*leaf)->left = NULL;
(*leaf)->right = NULL;
}
else if(value < (*leaf)->value)
{
insert( value, &(*leaf)->left );
}
else if(value > (*leaf)->value)
{
insert( value, &(*leaf)->right );
}
}

Related

function to delete node in a BST of strings

i'm having a problem in this code. its function is to go through a BST of strings and delete the nodes that satisfy some conditions (if in the word in the node there's an instance of the banned character, the node needs to be deleted). the problem is that it seg-faults in scrematurabanned2 because in the last recursive call it tries to access a node that is not existant and seg-faults. how can i fix this?
sorry in advance if there's not a lot of code in this question but this is a huge program and these are the parts that i think are responsible for the problem
struct node {
char *value;
struct node *p_left;
struct node *p_right;
};
int CmpStr(const char *a, const char *b)
{
return (strcmp (a, b));
}
void inserisciInAlbero2(char* key, struct node** leaf, Compare cmp) {
int res;
if( *leaf == NULL ) {
*leaf = (struct node*) malloc(sizeof( struct node ) );
(*leaf)->value = malloc( strlen (key) +1 );
strcpy ((*leaf)->value, key);
(*leaf)->p_left = NULL;
(*leaf)->p_right = NULL;
} else {
res = cmp (key, (*leaf)->value);
if( res < 0)
inserisciInAlbero2( key, &(*leaf)->p_left, cmp);
else if( res > 0)
inserisciInAlbero2( key, &(*leaf)->p_right, cmp);
}
}
void scrematurabanned2(struct node *head, const char *bannedchar, int n){
if( head != NULL ) {
scrematurabanned2(head->p_left, bannedchar, n);
if(strpbrk(head->value,bannedchar)!=NULL)
{
head = deleteNode(head, head->value);
}
scrematurabanned2(head->p_right, bannedchar, n);
}
}
struct node * minValueNode(struct node* node) {
struct node* current = node;
while (current->p_left != NULL)
current = current->p_left;
return current;
}
struct node* deleteNode(struct node* root, char *key) {
if (root == NULL)
return root;
int cmp_result = strcmp(key, root->value);
if (cmp_result < 0)
root->p_left= deleteNode(root->p_left, key);
else if (cmp_result>0)
root->p_right= deleteNode(root->p_right, key);
else{
if (root->p_left==NULL) {
struct node *temp = root->p_right;
free(root);
return temp;
} else if(root->p_right==NULL){
struct node *temp = root->p_left;
free(root);
return temp;
}
struct node* temp = minValueNode(root->p_right);
strcpy(root->value, temp->value);
}
return root;
}
int main() {
struct node *BST = NULL;
inserisciInAlbero2("2rj9R", &BST, (Compare) CmpStr);
inserisciInAlbero2("2rF9d", &BST, (Compare) CmpStr);
inserisciInAlbero2("2rq9R", &BST, (Compare) CmpStr);
inserisciInAlbero2("2ft9R", &BST, (Compare) CmpStr);
scrematurabanned2(BST, 'r', 5));

Delete a Node which is multiple of a given number with recursion [C programming]

I'm finding troubles trying to implement a function, this is what the program should do:
The user must first input an integer number (this number is not added to the list).
Then, I have to write a function which deletes recursively all the nodes in the list that are multiple of the input number.
This is my current code:
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
#define bool int
typedef struct node {
int data;
struct node *next;
} Node;
void addToHead(Node **head, int value);
void printList(Node *head);
bool isMultipleOf(int value, int n);
void deleteMultipleOfNNodes(Node **head, int n);
int main() {
// Create head
Node *head = NULL;
int loop = true;
int input;
// The value whose multiples must be deleted from the list
int n;
scanf("%d", &n);
while (loop) {
scanf("%d", &input);
// End loop - print list
if (input < 0) {
deleteMultipleOfNNodes(&head, n);
printList(head);
loop = false;
} else {
// Add value to the head
addToHead(&head, input);
}
}
return 0;
}
void addToHead(Node **head, int value) {
Node *temp;
if (*head != NULL) {
// Create new node
Node *newNode = (Node*) malloc(sizeof(Node));
// Set new node data
newNode -> data = value;
// New node links to the head
newNode -> next = *head;
// New node is now the head of the list
*head = newNode;
} else {
// Create head
*head = (Node*) malloc(sizeof(Node));
// Set head data
(*head) -> data = value;
// Head links to NULL
(*head) -> next = NULL;
}
}
void printList(Node *head) {
Node *temp = head;
while (temp != NULL) {
if (temp -> next != NULL) {
printf("%d -> ", temp->data);
} else {
printf("%d -> NULL", temp -> data);
}
temp = temp->next;
}
}
bool isMultipleOf(int value, int n) {
// While the value is greater than zero, keep on subtracting the number
while (value > 0) {
value -= n;
}
return (value == 0);
}
void deleteMultipleOfNNodes(Node **head, int n) {
// ========= CODE ================
}
Thank you in advance for your help!
The function can look very simple
void deleteMultipleOfNNodes( Node **head, int n )
{
Node *tmp = *head;
if ( tmp != NULL )
{
tmp->data % n == 0 ? ( *head ) = ( *head )->next, free( tmp )
: ( void )( head = &( *head )->next );
deleteMultipleOfNNodes( head, n );
}
}
Pay attention to that this function
bool isMultipleOf(int value, int n) {
// While the value is greater than zero, keep on subtracting the number
while (value > 0) {
value -= n;
}
return (value == 0);
}
is invalid in general case because either value or n can be negative.
So define the function like
bool isMultipleOf( int value, int n )
{
return value % n == 0;
}
In this case the function above can be rewritten like
void deleteMultipleOfNNodes( Node **head, int n )
{
Node *tmp = *head;
if ( tmp != NULL )
{
isMultipleOf( tmp->data, n ) ? ( *head ) = ( *head )->next, free( tmp )
: ( void )( head = &( *head )->next );
deleteMultipleOfNNodes( head, n );
}
}
The function addToHead is too complicated. It can be written the following way
bool addToHead(Node **head, int value)
{
Node *newNode = malloc( sizeof( Node ) );
bool success = newNode != NULL;
if ( success )
{
newNode -> data = value;
newNode -> next = *head;
*head = newNode;
}
return success;
}
Here is a demonstrative program. It contains only those functions that are required to demonstrate the recursive function.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct node {
int data;
struct node *next;
} Node;
bool addToHead(Node **head, int value)
{
Node *newNode = malloc( sizeof( Node ) );
bool success = newNode != NULL;
if ( success )
{
newNode -> data = value;
newNode -> next = *head;
*head = newNode;
}
return success;
}
bool isMultipleOf( int value, int n )
{
return value % n == 0;
}
void deleteMultipleOfNNodes( Node **head, int n )
{
Node *tmp = *head;
if ( tmp != NULL )
{
isMultipleOf( tmp->data, n ) ? ( *head ) = ( *head )->next, free( tmp )
: ( void )( head = &( *head )->next );
deleteMultipleOfNNodes( head, n );
}
}
void printList( const Node *head )
{
for ( ; head != NULL; head = head->next )
{
printf( "%d --> ", head->data );
}
puts( "NULL" );
}
int main(void)
{
Node *head = NULL;
const int N = 10;
for ( int i = N; i != 0; i-- )
{
addToHead( &head, i );
}
printList( head );
deleteMultipleOfNNodes( &head, 2 );
printList( head );
return 0;
}
Its output is
1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 7 --> 8 --> 9 --> 10 --> NULL
1 --> 3 --> 5 --> 7 --> 9 --> NULL

exc bad access C

I am making a simple BST and, in the add_to_bst() function, it is throwing an error in the first line when referencing the object's value.
CODE
typedef struct node {
int value;
struct node* leftChild;
struct node* rightChild;
} BSTNode;
BSTNode *new_BSTNode(int val) {
BSTNode *this = (BSTNode *) malloc(sizeof(BSTNode));
this->value = val;
this->leftChild = (BSTNode * ) malloc(sizeof(BSTNode));
this->rightChild = (BSTNode * ) malloc(sizeof(BSTNode));
this->leftChild = NULL;
this->rightChild = NULL;
return this;
}
typedef struct bst {
BSTNode * root;
} BST;
BST *new_BST(int root_val) {
BST *this = (BST *) malloc(sizeof(BST));
this->root = (BST * ) malloc(sizeof(BSTNode));
this->root->value = root_val;
// this->root->value = (int *) malloc(sizeof(int));
return this;
}
int node_get(BSTNode *n, int i) {
if (n == NULL) return -1;
if (i == n-> value) return 1;
if (i > n-> value) return node_get(n->rightChild, i);
else return node_get(n->leftChild, i);
}
int bst_get(BST *bst, int i) {
return node_get(bst->root, i);
}
void add_to_bst_node(int i, BSTNode *to) {
int n = to->value; // <--- ERR
printf("\nBST VAL: %d", n);
if (i > n) {
if (to->rightChild == NULL)
to->rightChild = new_BSTNode(i);
else
add_to_bst_node(i, to->rightChild);
} else {
if (to->leftChild == NULL)
to->leftChild = new_BSTNode(i);
else
add_to_bst_node(i, to->leftChild);
}
}
void add_to_bst(BST *tree, int i) {
if (tree->root != NULL) {
add_to_bst_node(i, tree->root);
} else {
tree->root = new_BSTNode(i);
}
}
int main() {
BST *bst = new_BST(10);
add_to_bst(bst, 10);
}
RUN MSG:
0x7fa64fc00690
0x7fa64fc00640
First Val: 10
Process finished with exit code 11
BUILD ERR:
BSTNode *new_BSTNode(int val) {
BSTNode *this = (BSTNode *) malloc(sizeof(BSTNode));
this -> value = val;
this -> leftChild = (BSTNode * ) malloc(sizeof(BSTNode));
this -> leftChild = (BSTNode * ) malloc(sizeof(BSTNode));
return this;
}
This leaves this->rightChild uninitialized and leaves this->leftChild pointing to uninitialized garbage. Neither of these issues is fixed in the code that calls new_BSTnode.
void add_to_bst_node(int i, BSTNode *to) {
int n = to -> value; // <------ ERROR
Not surprising, since to comes from leftChild and rightChild, both of which are broken by the logic of new_BSTNode.
Also:
BST *new_BST(int root_val) {
BST *this = (BST *) malloc(sizeof(BST));
this -> root = (BST * ) malloc(sizeof(BSTNode));
this -> root -> value = root_val;
// this -> root -> value = (int *) malloc(sizeof(int));
return this;
}
This doesn't set this->root->leftChild or this->root->rightChild either, so again, they're garbage that gets passed to add_to_bst_node as to.
The creation of the new node, and insertion into the tree seems incorrect.
A new node should not allocate space for the left and right subtrees. Since new nodes are always added to the extremities, they never have subtrees when new anyway.
BSTNode *new_BSTNode( int val )
{
BSTNode *this = ( BSTNode * ) malloc( sizeof( BSTNode ) );
if ( this != NULL )
{
this->value = val;
this->leftChild = NULL;
this->rightChild = NULL;
}
return this;
}
Using a recursive algorithm when inserting new data allows the code to "walk" the tree, finding the correct place for insertion.
void add_to_bst_node( int value, BSTNode *to )
{
if (to != NULL)
{
if (value > to->value)
{
// Add to child-right subtree
if (to->rightChild == NULL)
{
// right-tree is empty, create it
to->rightChild = new_BSTNode( value );
}
else
{
// add it somewhere on the right-side (recursively)
add_to_bst_node( value, to->rightChild );
}
}
else // if (i <= to->value)
{
// Add to child-left subtree
if (to->leftChild == NULL)
{
// left-tree is empty, create it
to->leftChild = new_BSTNode( value );
}
else
{
// add it somewhere on the right-side (recursively)
add_to_bst_node( value, to->leftChild );
}
}
}
}
A tree is just a node. Making a separate structure for a "tree" is just extra work.
typedef BSTNode BST;
So the creation of a tree, is just the creation of a node:
BST *new_BST( int value )
{
return new_BSTNode( value );
}
The branch in add_to_BST() always chooses the tree->root != NULL if it was initialised error-free. Then the add_to_BST_node() dereferences garbage, (as the other answers have pointed out); here is a graphical representation of the memory allocating functions,
And,
I recommend thinking about what the states are in ones system and drawing them out first so one doesn't fall into an invalid state. Also, if one is doing a constructor, it's a good idea to initialise the entire structure.

C- Binary Search Tree

I am trying to build a a binary search tree. But I am not getting the correct output when performing the different traversals.
typedef struct binary_search_tree{
struct binary_search_tree *lchild;
int data;
struct binary_search_tree *rchild;
}bst_t;
#define ALLOCATE (bst_t*)malloc(sizeof(bst_t))
Here is the insert function:
void insert(bst_t *ptr,int data){
if( ptr->data < data){
if ( ptr->lchild == NULL ){
ptr->lchild = ALLOCATE;
ptr->lchild->data = data;
return;
}else
insert(ptr->lchild,data);
}else{
if ( ptr->rchild == NULL ){
ptr->rchild = ALLOCATE;
ptr->rchild->data = data;
return;
}else
insert(ptr->rchild,data);
}
}
Is this function correct?
I am sending the address of root while calling that function.
The problem is the ALLOCATE macro. It doesn't do nearly enough to properly allocate and initialize a new node. I suggest creating a newNode function that allocates memory for the node, and then initializes all of the members of the structure, like this
bst_t *newNode(int data)
{
// allocation and error checking
bst_t *node = malloc(sizeof(bst_t));
if ( node == NULL )
{
fprintf(stderr, "out of memory\n");
exit( 1 );
}
// initialize the members of the structure
node->lchild = NULL;
node->data = data;
node->rchild = NULL;
return node;
}
Then the insert function can be simplified to this
void insert(bst_t *ptr,int data)
{
if( ptr->data < data){
if ( ptr->lchild == NULL )
ptr->lchild = newNode(data);
else
insert(ptr->lchild,data);
}else{
if ( ptr->rchild == NULL )
ptr->rchild = newNode(data);
else
insert(ptr->rchild,data);
}
}

BST build tree double pointers

I am unsure how to set a pointer to a pointer to build a tree. Like once I have traveled to a leaf and call insert, how should I insert another element calling insert with the root node or the address of the root pointer? I think the problem with this function is the name root where that should be the double pointer right?
#include "bst.h"
#include <stdio.h>
#include <stdlib.h>
//arbitrary list of temp nodes
TreeNode *new_node, *root, *tmp, *parent;
int elemArray[100], i1, i2, i0;
int main( int argc, char *argv[] ) {
//Throw error is *Argv[] is not an integer
//assuming it was an integer
int cnt = atoi( argv[1] );
printf( "number is %d\n", cnt );
//
printf("Enter %i integer values to place in tree:\n", cnt);
for ( i1 = 0; i1 < cnt; ++i1) {
scanf( "%d", &elemArray[i1] );
}
//first ouput "INput Values"
printf( " Input Values:\n " );
for ( i2 = 0; i2 < cnt; ++i2) {
printf( "%d\n", elemArray[i2] );
}
TreeNode** root = (TreeNode*)malloc(sizeof(TreeNode*));
buildTree(root, elemArray, cnt );
printf( "Preorder:\n ");
//traverse
//TreeNode* tempN = malloc(sizeof(TreeNode*));
//tempN->data= 5;
traverse( root, PREORDER);
//traverse a single node
printf( "Inorder:\n ");
printf( "Postorder:\n ");
//Build tree with each element
return 0;
}
This is the .h file
/// The definition of the tree structure
typedef struct TreeNode {
int data ; // the data stored in the node
struct TreeNode* left ; // node's left child
struct TreeNode* right ; // node's right child
} TreeNode;
/// The three supported traversals
typedef enum {
PREORDER, // parent -> left -> right
INORDER, // left -> parent -> right
POSTORDER // left -> right -> parent
} TraversalType;
and lastly the traverse function so far as it failed the first test.
void traverse( const TreeNode* root, const TraversalType type ) {
if ( type == PREORDER) {
if (root != NULL)
{
printf("%d", root->data);
traverse( root->left, PREORDER);
traverse( root-> right, PREORDER);
}
}
}
void build_tree(TreeNode** root, const int elements[], const int count) {
TreeNode* node = malloc(sizeof(TreeNode*));
node->left = node ->right = NULL;
*root = node;
for ( int i0 = 0; i0 < count; ++i0 ){
TreeNode* node = malloc(sizeof(TreeNode*));
*root = node;
node->data = elements[cnt];
insertNode( &(*root), &node );
}
}
Why is the insertNode getting the errors (multiple) and I don't know which is the pointer and which is the struct. GUYS ANY HINT WILL BE HELPFUL PLEASE?
bst.c:94:20: error: request for member 'left' in something not a structure or union
insert(root->left, new_node);
void insertNode(TreeNode** root, TreeNode* new_node) {
if (new_node-> data < &root-> data) {
if (&root-> left == NULL)
&root-> left == new_node;
else
insert(root->left, new_node);
}
if (new_node->data > &root->data) {
if(&root-> right ==NULL)
&root->right = new_node;
else
insert(&root->right, new_node);
}
}
SO for Edit 2: I do have a header file which has a build_Tree(**root, elems[], sizeofElem[]), which means i need a helper function insert. Yes is would be easier to add by input starting*.
Edit 1
#include "bst.h"
#include <stdio.h>
#include <stdlib.h>
//arbitrary list of temp nodes
TreeNode *new_node, *root, *tmp, *parent, *current;
int elemArray[5], i1, i2, i0;
/*
Insert a new node into the tree by referencing the root and using recursion
*/
TreeNode* getN(int dataElem) {
TreeNode *newNode = malloc(sizeof(*newNode));
if (newNode != NULL)
{
newNode->data = dataElem;
newNode->left = NULL;
newNode->right = NULL;
}
return newNode;
}
/** This func should just be the root of the tree in the parameter,
but I like the idea of a pointer becuase it helps to create a tempory
pointer rather than newNode
**/
TreeNode* addNodeToTree(TreeNode *root, int data) {
TreeNode *current = *root; //define the current pointer to the root always
TreeNode *parent = *root
TreeNode *newNode = getN(data);
if (*root == NULL)
{
printf("First Node");
*root = newNode;
}
else
{
while(current != NULL)
{
parent = current;
if (current->data > data)
current = current->left;
else if (current->data < data)
current = current->right;
}
if (parent->data > data)
parent->left = newNode;
else if (parent->data < data)
parent->right = newNode;
}
}
void build_Tree(TreeNode** root, const int elements[], const int count) {
*root = malloc(sizeof(TreeNode));
for ( i0 = 0; i0 < count; ++i0 ){
printf("%d\n", elements[count]);
addNodeToTree(&root, elements[count]);
}
}
int main( int argc, char *argv[] ) {
//Throw error is *Argv[] is not an integer
//assuming it was an integer
int cnt = atoi( argv[1] );
printf( "number is %d\n", cnt );
//
printf("Enter %i integer values to place in tree:\n", cnt);
for ( i1 = 0; i1 < cnt; ++i1) {
scanf( "%d", &elemArray[i1] );
}
//first ouput "INput Values"
printf( " Input Values:\n " );
for ( i2 = 0; i2 < cnt; ++i2) {
printf( "%d\n", elemArray[i2] );
printf("building tree0\n");
}
printf("building tree\n");
TreeNode** root = (TreeNode**)malloc(sizeof(TreeNode*));
TreeNode *root = NULL;
build_Tree(root, elemArray, cnt );
printf( "Preorder:\n ");
//traverse
//TreeNode* tempN = malloc(sizeof(TreeNode*));
//tempN->data= 5;
traverse( *root, PREORDER); //pass the pointer of root to traverse the tree
//traverse a single node
printf( "Inorder:\n ");
printf( "Postorder:\n ");
//Build tree with each element
return 0;
}
void traverse( const TreeNode* root, const TraversalType type ) {
if ( type == PREORDER) {
if (root != NULL)
{
printf("%d", root->data);
traverse( root->left, PREORDER);
traverse( root-> right, PREORDER);
}
}
}
/**
void insertNode(TreeNode** root, TreeNode* new_node) {
if (new_node-> data < *root-> data) {
if (*root-> left == NULL)
*root-> left == new_node;
else
insert(*root->left, new_node);
}
if (new_node->data > *root->data) {
if(*root-> right ==NULL)
*root->right = new_node;
else
insert(*root->right, new_node);
}
}
**/
//question1: what is the
Edit 2 for main and build_tree
void build_Tree(TreeNode** root, const int elements[], const int count) {
//*root = malloc(sizeof(TreeNode));
for ( i0 = 0; i0 < count; i0++ ){
//create the node
//
TreeNode *current = *root; //define the current pointer to the root always
TreeNode *parent = *root;
//dont create node
int data = elements[i0];
TreeNode *newNode = getN(data);
if (*root == NULL)
{
printf("First Node %d\n", elements[i0]);
*root = newNode;
}
else
{
printf("Next Node %d\n", elements[i0]);
while(current != NULL)
{
parent = current;
if (current->data > data)
current = current->left;
else if (current->data < data)
current = current->right;
}
if (parent->data > data)
parent->left = newNode;
else if (parent->data < data)
parent->right = newNode;
}
//return root;
}
}
TreeNode* getN(int dataElem) {
TreeNode *newNode = malloc(sizeof(*newNode));
if (newNode != NULL)
{
newNode->data = dataElem;
newNode->left = NULL;
newNode->right = NULL;
}
return newNode;
}
int main( int argc, char *argv[] ) {
//Throw error is *Argv[] is not an integer
//assuming it was an integer
int cnt = atoi( argv[1] );
printf( "number is %d\n", cnt );
//
printf("Enter %i integer values to place in tree:\n", cnt);
for ( i1 = 0; i1 < cnt; ++i1) {
scanf( "%d", &elemArray[i1] );
}
//first ouput "INput Values"
printf( " Input Values:\n " );
for ( i2 = 0; i2 < cnt; ++i2) {
printf( "%d\n", elemArray[i2] );
printf("building tree0\n");
}
printf("building tree\n");
TreeNode* root; //= malloc(sizeof(TreeNode*));
root = NULL;
build_Tree(&root, elemArray, cnt );
printf( "Preorder:\n ");
//traverse
//TreeNode* tempN = malloc(sizeof(TreeNode*));
//tempN->data= 5;
//traverse( *root, PREORDER); //pass the pointer of root to traverse the tree
//traverse a single node
printf( "Inorder:\n ");
printf( "Postorder:\n ");
//Build tree with each element
return 0;
}
Say you created a function addNodeToTree(TreeNode *root, int data), pass the root node, and data to it as argument.
Now inside this function, simply create another variable say TreeNode *current = root which will help us basically to traverse the tree and place the node at its respective position, and TreeNode *newNode = NULL(this will become the new node, which is to be inserted).
Now before moving ahead, to actually place the node, we will first check, if the root is not null, i.e. the tree is EMPTY. For that, we will test:
if (root == NULL)
{
newNode = malloc(sizeof(*newNode)); // else we can make a function for this
// thingy too. Creating a function too,
// for you to look at.
root = newNode;
}
If the tree is not EMPTY, i.e. it contains a node already, then we will traverse the tree to find the place, where to put the new node. So the else part, will be like:
else
{
parent = current = root;
// This loop will actually help us, find the `parent`,
// of the `newNode`(which is to be inserted)
while (current != NULL)
{
parent = current;
if (current->data > data)
current = current->left;
else if (current->data < data)
current = current->right;
}
// Now once, we have found, the node, under which the
// newNode will be placed, now we have to check, whether
// newNode will become a `left child/right child` of the
// parent.
newNode = getNewNode(data);
if (parent->data > data)
parent->left = newNode;
else if (parent->data < data)
parent->right = newNode;
return root;
}
TreeNode * getNewNode(int data)
{
TreeNode *newNode = malloc(sizeof(*newNode));
if (newNode != NULL)
{
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
}
return newNode;
}
Now the newNode has been inserted, and you can simply traverse in any order to see the Tree.
EDIT 1:
Here is one working example, just see if this makes sense. Else please do ask any question, that might may arise.
#include <stdio.h>
#include <stdlib.h>
typedef struct TREENODE
{
int data;
struct TREENODE *left;
struct TREENODE *right;
}TreeNode;
void display(TreeNode *node)
{
printf("*********************************\n");
printf("Address of Node: %p\n", node);
printf("Data: %d\n", node->data);
printf("Left Child: %p\n", node->left);
printf("Right Child: %p\n", node->right);
printf("*********************************\n");
}
TreeNode * getNewNode(int data)
{
TreeNode *newNode = malloc(sizeof(*newNode));
if (newNode != NULL)
{
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
}
return newNode;
}
int getIntData(char *message)
{
int value = 0;
char buffer[BUFSIZ] = {'\0'};
fputs(message, stdout);
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d", &value);
return value;
}
TreeNode * addNodeToTree(TreeNode *root, int data)
{
TreeNode *current = root, *parent = root;
TreeNode *newNode = getNewNode(data);
if (root == NULL)
{
root = newNode;
}
else
{
while(current != NULL)
{
parent = current;
if (current->data > data)
current = current->left;
else if (current->data < data)
current = current->right;
}
if (parent->data > data)
parent->left = newNode;
else if (parent->data < data)
parent->right = newNode;
}
return root;
}
void inOrderTraversal(TreeNode *root)
{
if (root != NULL)
{
inOrderTraversal(root->left);
display(root);
inOrderTraversal(root->right);
}
}
int main(void)
{
TreeNode *root = NULL;
int data = 0;
data = getIntData("Enter Data: ");
root = addNodeToTree(root, data);
data = getIntData("Enter Data: ");
root = addNodeToTree(root, data);
data = getIntData("Enter Data: ");
root = addNodeToTree(root, data);
inOrderTraversal(root);
return EXIT_SUCCESS;
}
EDIT 2:
To make addNodeToTree(...), implement pointer to a pointer, one simply needs to change the function as:
void addNodeToTree(TreeNode **root, int data)
{
TreeNode *current = *root;
TreeNode *parent = *root;
TreeNode *newNode = getNewNode(data);
if (*root == NULL)
{
*root = newNode;
}
else
{
// same as before, just don't return anythingy, from the function.
// As the function uses pointer to a pointer, hence whatever changes
// are done, here will be reciprocated in the main function automatically
}
// no need to return anythingy
}
And the call from main will now look like:
int main(void)
{
TreeNode *root = NULL;
int data = 0;
data = getIntData("Enter Data: ");
addNodeToTree(&root, data);
// Just see the call to addNodeToTree(...), the rest is same, as before
}
EDIT 3:
In order to take elements from an array instead of adding them directly to tree, just change the main method to this form:
int main(void)
{
TreeNode *root = NULL;
int element[5] = {19, 11, 5, 28, 25};
int size = sizeof(element) / sizeof(element[0]);
int counter = 0;
for (counter = 0; counter < size; ++counter)
{
addNodeToTree(&root, element[counter]);
}
inOrderTraversal(root);
return EXIT_SUCCESS;
}

Resources