0

so i was trying to make a binary tree program. just inserting and deleteing. some how i messed up. i think insertion is ok till level 1 after that stays on level 1 only.

also the function to delete the whole tree is not working.
it only deletes node at level 0 only.
first i thought that assigning the value to pointer as 0 will make it null pointer but i was not able to comapre it with 0. it was having some other value that compiler assigned it.

i have tried to test it a lot of times but i think i need help now.

#include<iostream.h>
#include<conio.h>

struct tree{
int data;
tree *left;
tree *right;
};

tree *root=0;
tree *nullptr=root;
int level=-1;

tree* createnode()
    {
    tree *ptr=new tree;
    ptr->left=0;
    cout<<"\ncreating left ptr "<<ptr->left;
    ptr->right=0;
    cout<<"\ncreating right ptr "<<ptr->right;
    return ptr;
    }

void deletetree(tree *ptr)
    {
    cout<<"\nptr value = "<<ptr;
    if(ptr!=0||nullptr!=ptr)
        {
        cout<<"\nleft prt "<<ptr->left;
        cout<<"\nright prt "<<ptr->right;
        deletetree(ptr->left);
        deletetree(ptr->right);
        delete ptr;
        cout<<"\n"<<ptr<<" deleted! " ;
        }
    }

void insert(int a,tree *ptr)
    {
    level++;
    if(ptr==root&&root==0)
        {
        ptr = createnode();
        root=ptr;
        ptr->data=a;
        cout<<"\nnode "<<a<<" inserted at level "<<level<<"\nvalue in ptr root is "<<ptr<<" "<<root<<endl;
        }
    else if(ptr==0)
        {
        ptr=createnode();
        ptr->data=a;
        cout<<"\nnode "<<a<<" inserted at level "<<level<<"\nvalue in ptr root is "<<ptr<<" "<<root<<endl;
        }


     else if(a<(ptr->data))
        {
        cout<<endl<<ptr->left<<" memory at left ptr and level = "<<level;
        insert(a,ptr->left) ;
        }
     else if(a>(ptr->data))
        {
        cout<<endl<<ptr->right<<" memory at right ptr and level = "<<level;
        insert(a,ptr->right);
        }
     level=-1;
    }
void main()
{
char ch='y';
int d;
clrscr();
int data;
while (ch=='y')
    {
    cout<<"\n\n\t\tEnter the element : ";
    cin>>d;
    insert(d,root);
    cout<<"\n\t\tWant to enter more?(y/n)";
    cin>>ch;
    }
deletetree(root);
getch();
}

Edited by Rishabh876: spell check

1
Contributor
2
Replies
5
Views
5 Years
Discussion Span
Last Post by Rishabh876
0

k i think i figured it out. during insertion of new node. the pionter that i am passing are call by value so all the changes i am making are in other pointer and not the pointer i am passing. how can i pass a pointer by refrence. its sound too strange to even write this.

0

so i have solved it myself. nobody replied. its just that i didnt take call by refrence in insertion for the pointer

Edited by Rishabh876

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.