Ahashan Alam Sojib
Ahashan Alam Sojib

Reputation: 27

Binary search tree Inorder tranversal recursive function doesn't work correctly

I am trying to create a binary search tree in C++ with struct. In this code the 'inorder' function doesn't work. My code is below:

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node{
struct node *left, *right,*root;
int data,count;
}*new_node,*tree, *temp,*ruff;
void root_create(){
tree = (struct node *)malloc(sizeof(struct node));
tree->root = NULL;
tree->count=0;
}
void node_create(int data){
new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = data;
new_node->left=NULL;
new_node->right=NULL;
}
node * node_insert(node *tree){
temp = tree->root;
if(temp==NULL){
    temp = new_node;
    temp->count++;
    return temp;
}
else if(temp->left==NULL and temp->right==NULL){
    if(temp->data > new_node->data){
        tree->root->left =  new_node;
    }
    else if(tree->root->data <= new_node->data){
        tree->root->right =  new_node;
    }
    temp->count++;
    return temp;
}
else{
    if(temp->data <= new_node->data){
        return node_insert(temp->right);
    }
    if(temp->data > new_node->data){
        return node_insert(temp->left);
    }
}
}
void inorder(node *){
if(ruff == NULL){
    cout<<"No Data!"<<endl;
    return;
}
if(ruff->left!=NULL){
    inorder(ruff->left);
}
cout<< ruff->data<<endl;

if(ruff->right!=NULL){
    inorder(ruff->right);
}
cout<< ruff->data<<endl;
}
int main()
{
int data=321;
root_create();
node_create(data);
tree->root = node_insert(tree);
data=123;
node_create(data);
tree->root = node_insert(tree);
ruff = tree->root;
inorder(tree);
return 0;
}

In main function I've created two node and attached them to tree->root. I can access the data from tree->root. But when I call inorder function, it doesn;t show any output.

Upvotes: 1

Views: 146

Answers (1)

Mark Bessey
Mark Bessey

Reputation: 19782

You're using the static variable "ruff" in your inorder function, rather than the passed parameter, which you've neglected to give a name to.


When you've got it working, the inorder() function is very simple:

  1. First you call inorder() on the left pointer of the current node.
  2. Then, you print the value of the current node.
  3. Finally, you call inorder() on the left pointer of the current node.

In order for the recursion to end, you need to exit early from inorder() if the passed-in node* is NULL.

Upvotes: 1

Related Questions