-2

Hi guys I have a doubt in inserting a new node in BST. In the addNode module I am trying to insert an element in the BST, but each time while adding a new node it is adding to the same root node which I passed from main function initially without traversing inside the tree.

This is the code which I have written.

#include<stdio.h>
#include<stdlib.h>
#include<cstdio>
#include<iostream>
using namespace std;
struct node
{
    int data;
    struct node *left;
    struct node *right;
};
struct node* newNode(int data)
{
    node* temp = (node*)malloc(sizeof(struct node));
    //struct temp = new node;
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return(temp);
};
int addNode(node *dest, node *root)
{
    if(root == NULL)
    {
        cout<<"adding data to node for "<< dest->data<<endl;
        root = dest;
        cout<<"ROOT VALUE = root->data "<<root->data<<endl;
        return 1;
    }
    if(dest->data > root->data)
    {
        cout<<"Traverse right for "<<dest->data<<endl;
        addNode(dest, root->right);
    }
    else if(dest->data < root->data)
    {
        cout<<"Traverse left for "<<dest->data<<endl;
        addNode(dest, root->left);
    }
}
void printNodes(node *root)
{
    if(root != NULL)
    {
        printNodes(root->left);
        if(root->left != NULL && root->right != NULL)
            std::cout<< root->data <<" ";
        printNodes(root->right);
    }
}
int main()
{
    int i, j, k, flag;
    int arr[6] = {4, 2,8, 1, 0, 10};
    node *start = newNode(arr[0]);
    for(i = 1; i < 6; i++)
    {
        node *newOne = newNode(0);
        newOne->data = arr[i];
        cout<<"NODE DATA - start->data "<<start->data;
        if(addNode(newOne, start))
            std::cout<<"\nNode added"<<endl;
    }
    printNodes(start);
    return 1;
}

I am quite new to trees concept as well as pointers concept in trees. Any help is appreciated and thank you.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
susil95
  • 300
  • 3
  • 5
  • 16
  • There's nothing special about pointers. Assigning to a pointer parameter is no different from assigning to an `int` parameter. – molbdnilo Oct 18 '17 at 18:27

1 Answers1

0

... but each time while adding a new node it is adding to the same root node

This is because you are adding it always to the same root, as here

if(addNode(newOne, start))

start is always the same. You could make addNode return the new root and call it like that:

start = addNode(newOne,start);

I'll leave it to you to implement it.

Note that parameters are always passed by value in c++ (unless you pass-by-reference), thus changing the parameter inside the method, root = dest;, has no effect on the start in main.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185