does anyone know how save a value into a binary tree on the left or right side?
for example we have 2 structs:
struct A
{
int a;
struct A *left;
struct A *right;
}
struct B
{
A *root;
}
and we have a function:
void insert(B *tree, int value)
{
if(tree== NULL)
{
tree= (B*) malloc (sizeof(B));
}
else if(tree!=NULL)
{
tree->root->a = value;
tree->root->left = NULL;
tree->root->right = NULL;
}
now we have the root...
but how to initiliase the value on the right and left side?
else if(tree->apointer->a< value)
{
tree->root->left = value // with & wont work cause is a pointer to integer
}
does anyone know ??
Thanks in advance
With tree= (B*) malloc (sizeof(B));, you create an object of type B, but you do not create an object of type A to which tree->root could point to. Accessing tree->root->a or the other members of root then is undefined behaviour;
You could write:
tree = malloc (sizeof(B));
tree->root = malloc(sizeof(A));
I think there is no sense to discuss your code.:) Even structure definitions are written without semicolons.
Taking into account these structure definitions
struct A
{
int value;
struct A *left;
struct A *right;
};
struct B
{
struct A *root;
};
and assuming that in main there is the following declaration of the tree
int main( void )
{
struct B tree = { NULL };
//...
then the function insert can be defined the following way
int insert( struct B *tree, int value )
{
struct A **node = &tree->root;
while (*node)
{
if (value < (*node)->value)
{
node = &(*node)->left;
}
else
{
node = &(*node)->right;
}
}
*node = malloc(sizeof(struct A));
int success = *node != NULL;
if ( success )
{
(*node)->value = value;
(*node)->left = NULL;
(*node)->right = NULL;
}
return success;
}
The function can be called like
insert( &tree, value );
or its call can be enclosed in an if statement
if ( insert( &tree, value ) ) { /*...*/ }
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 );
}
}
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;
}
Here i have written a code which inserts numbers in Binary tree. But it gives segmentation fault error.
And also it says " note: expected ‘struct tree *’ but argument is of type ‘struct node *’" in line 8.
Here is the code :-
#include<stdio.h>
#include<stdlib.h>
struct tree{
int data;
struct tree *left;
struct tree *right;
};
struct tree* insert(struct tree* node, int data)
{
if(!node){
node=malloc(sizeof(struct tree));
node->data=data;
node->left=node->right=NULL;
return node;
}
else {
if(data>node->data){
node->right= insert(node->right,data);
return node;
}
else{
node->left= insert(node->left,data);
}
return node;
}
}
printtree(struct tree* node)
{
if(node){
printf("%d",node->data);
}
printtree(node->left);
printtree(node->right);
}
main()
{
int i,n;
struct tree *NODE;
NODE= insert(NODE,5);
NODE= insert(NODE,3);
NODE= insert(NODE,8);
printtree(NODE);
}
You use if( node ) but better to use if( node != NULL )
You use if( !node ) but better to use if( node == NULL )
It make code more readable.
You have so many mistakes - so ... I make it in my way (my code formating, etc.).
printtree(node->left); printtree(node->right); was outside if( node != NULL ){} so it try to get NULL->left and NULL->right
Tested - code works.
#include<stdio.h>
#include<stdlib.h>
struct tree{
int data;
struct tree *left;
struct tree *right;
};
struct tree* insert(struct tree* node, int data)
{
if( node == NULL ) {
node = malloc( sizeof(struct tree) );
node->data = data;
node->left = node->right = NULL;
} else {
if( data > node->data ){
node->right = insert(node->right, data);
} else {
node->left = insert(node->left, data);
}
}
return node;
}
void printtree(struct tree* node)
{
if( node != NULL ){
printf("%d\n", node->data);
printtree(node->left);
printtree(node->right);
}
}
int main()
{
struct tree *NODE = NULL;
NODE = insert(NODE, 5);
NODE = insert(NODE, 3);
NODE = insert(NODE, 8);
printtree(NODE);
return 0;
}
The local variable: struct tree* node; is not initialized, so the if (!node) test will have undefined behavior. Unless you assign it something or use it to hold a malloc'd node, the expression in the else block tries to dereference an uninitialized pointer.
You should also get used to idea that a tree can be considered a 'recursive' structure, so any node is a tree, and the top-level tree is simply a node. There's no good reason for two separate types here.
You are still making the error of passing NODE by value. If you want to modify it, you must use a pointer to that pointer.
#include<stdio.h>
#include<stdlib.h>
typedef struct t
{
int data;
struct t *left;
struct t *right;
}tree;
tree* insert(tree **node, int data)
{
if(!(*node))
{
*node=malloc(sizeof(tree));
(*node)->data=data;
(*node)->left=(*node)->right=NULL;
return *node;
}
else
{
if(data>(*node)->data)
{
(*node)->right = insert(&((*node)->right),data);
return *node;
}
else
{
(*node)->left = insert(&((*node)->left),data);
return *node;
}
}
}
void printtree(tree *node)
{
if(node)
{
printf("%d",node->data);
printtree(node->left);
printtree(node->right);
}
}
void freeMemory(tree *node)
{
if(node)
{
freeMemory(node->left);
freeMemory(node->right);
free(node);
}
}
int main()
{
tree *NODE = NULL;
NODE= insert(&NODE,5);
NODE= insert(&NODE,3);
NODE= insert(&NODE,8);
printtree(NODE);
freeMemory(NODE);
return 0;
}
Link: http://ideone.com/OpZWiC
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);
// ...
}