简体   繁体   中英

why this code is not inserting the nodes in binary search tree

Is there anything wrong in insert module. Its not adding the new node in tree. I am using pass-by-ref.

    #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

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

tNode* newNode (int data)
{
    tNode* temp = new tNode;
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

void insert (tNode*& root, int value)
{
    if (!root)
    {
        root = newNode (value);
    }
    else
    {
        if ( value > root->data )
            insert (root->right, value);
        else
            insert (root->left , value);
    }
}

void storeInorder (vector<int>& v, tNode* t)
{
    if (!t)
    {
        storeInorder (v, t->left);
        v.push_back(t->data);
        storeInorder (v, t->right);
    }
}

void printInOrder (tNode* t)
{
    if (!t)
    {
        printInOrder (t->left);
        cout << t->data << " ";
        printInOrder (t->right);
    }

}
int main() 
{

    vector <int> v = {10, 23, 41, 12, 55, 34, 17, 40, 19,3};
    tNode* bst = NULL;
    for (int i=0; i<v.size(); ++i)
    {
        insert (bst, v[i]);
    }

    printInOrder (bst);


    v.clear();
    storeInorder (v, bst);

    cout << v.size();

    for (int i=0; i<v.size(); ++i)
    {
        cout <<  v[i] << " ";
    }

    if (is_sorted (v.begin(), v.end()))
        cout << "everything fine";
    return 0;
}

There is an error in function printInOrder . When t is not null, print it. So it should be

if (t)

not

if (!t)

No problem in insert() . The problem results from printInOrder() with wrong check conditions, which should be:

void printInOrder(tNode *t)
{
    if (t)
    {
        printInOrder(t->left);
        cout << t->data <<" ";
        printInOrder(t->right);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM