edited by
655 views
1 votes
1 votes

Here is my code to create & traverse BST but it has got some problems possibly run time - No output being shown. Can anyone figure out problem?

#include <stdio.h>
#include <stdlib.h>

struct Node{
	int item;
	struct Node* left;
	struct Node* right;
};
struct Node* newNode(int item){
	struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
	newnode->item = item;
	newnode->left = NULL;
	newnode->right = NULL;
    return newnode;
}

void insert(struct Node* root,int item){
	if(root==NULL){
		root = newNode(item);
	}
	if(item < root->item)
		insert(root->left,item);
	else
		insert(root->right,item);
}

void inorder(struct Node* root){
	if(root!=NULL){
		inorder(root->left);
		printf("%d ",root->item);
		inorder(root->right);
	}
}

int main(){
	struct Node* root = NULL;
	insert(root,50);
	insert(root,30);
	insert(root,10);
	insert(root,40);
	inorder(root);
	return 0;
}
edited by

2 Answers

1 votes
1 votes
You have declare root in main when first insert call is made you are making 50 as root but while coming out of insert function you are not returning value of root back, so for main program root is still null
0 votes
0 votes
  • 1st mistake- Absence of else in the insert function.
  • 2nd Mistake- Pass by value without return to the insert function. 

The correct code is as follows, note that it is difficult to fix the same code using pointer to pointer as well. 

struct Node* insert(struct Node* root,int item){
	if(root== NULL)
		root = newNode(item);
	else if(item < root->item){
		root->left = insert(root->left,item);
	}
	else
		root->right = insert(root->right,item);
	return root;
}

then we need to update main() as well as follows. 

root = insert(root,50);

Related questions

0 votes
0 votes
1 answer
2
1 votes
1 votes
1 answer
3
0 votes
0 votes
1 answer
4