meetjatin88 0 Newbie Poster

Hello Everyone ,
Can some one please tell me what is wrong in my program.
This is basically a program to insert a new node in a binary search tree.

The thing is that my insert function is working correctly and the node is getting inserted
which i am verifying in the main program by the line

cout<<a.left->right->right->data;

The output of which is coming correctly i.e 5

but when i try to print a level order traversal of the binary tree some junk value is getting passed in place of the new node and the program is crashing

Can some one please have a look and explain to me what i am doing wrong and how can in the main program the correct value is getting displayed.

// CTest.cpp : Defines the entry point for the console application.
//

#include<iostream>
#include<string>
#include<conio.h>
#include<array>
#include<stack>
#include<sstream>
#include<algorithm>
#include<vector>
#include<ctype.h>//isdigit
#include<deque>
#include<queue>
#include<map>
using namespace::std;

struct BST
{
    int data;
    BST *left;
    BST *right;

    BST(int d,struct BST* l,BST *r):data(d) , left(l) ,right(r) 
    {
    }
};


void levelOrder(struct BST *root)
{
    struct BST *temp=NULL;
    int count =0;
    deque<struct BST*> dq;
    if(!root)
    {
        return;
    }
     dq.push_back(root);
     count=dq.size();
     while(!dq.empty())
     {
         temp=dq.front();
         cout<<temp->data<<" ";
         if(temp->left)
         {
             dq.push_back(temp->left);
         }
         if(temp->right)
         {
             dq.push_back(temp->right);
         }
         dq.pop_front();
         if(--count==0)
         {
             cout<<endl;
             count=dq.size();
         }
     }
}

void Insert(struct BST*root,int data)
{
    struct BST temp(data,NULL,NULL);
    if(!root)
    {
        return;
    }
    while(root)
    {
        if((root)->data >data)
        {
            (root)=(root)->left;
            if(!(root)->left)
            {
                (root)->left=&temp;
                break;
            }
        }
        else
        {
            (root)=(root)->right;
            if(!(root)->right)
            {
                (root)->right=&temp;
                break;
            }
        }
    }
}
int main()
{
    deque<struct BST> dq1,dq2;

    BST e(4,NULL,NULL);
    BST f(3,NULL,NULL);
    BST d(1,&f,NULL);
    //BST g(4,NULL,NULL);
    BST b(2,&d,&e);
    BST c(8,NULL,NULL);
    BST a(6,&b,&c);
    levelOrder(&a);
    Insert(&a,5);
    cout<<a.left->right->right->data;
    cout<<endl;
    levelOrder(&a);
    _getch();
    return 0;

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.