0

Designed my first BST but for some reason it segfaults when I add more than 2 items. Cant seem to figure out why. I think int has to do with my insert function within Node. The main stops working after t.insert(5) and t.insert(10);

Tree.CPP

#include <iostream>
#include "Tree.h"
 

using namespace std;

Node::Node(int obj)
{
    value = obj;
}
void Node::set(int obj){
    int value = obj;
}

bool Node::member(int obj) const{
    if(obj<value){
        if(left == NULL)
            return false;
        else
            return left -> member(obj);
    }
    if(obj>value){
        if(right == NULL)
            return false;
        else
            return right -> member(obj);
    }
return true;
}

void Node::insert(int obj){
    if(obj < value){
        if(left == NULL)
            left = new Node(obj);
        else
            left -> insert(obj);
    }
    if(obj > value){
        if(right == NULL)
            right = new Node(obj);
        else
            left -> insert(obj);
    }
}

Tree::Tree()
{
    root = NULL;
}

bool Tree::member(int obj) const{
    if(root == NULL)
        return false;
    else
        return root -> member(obj);

}

void Tree::insert(int obj){
    if(root == NULL)
        root = new Node(obj);
    else
        root -> insert(obj);
}

I had to convert this code from SmallTalk. I don't know if the code was 100% translatable. That could be the issue as well.

jayboiq
  • 9
  • 1
  • `# ifndef TREE_H # define TREE_H class Node { int value; Node *left; Node *right; public: Node(int); void insert(int); bool member(int) const; void set(int); }; class Tree { Node *root; public: Tree(); void insert(int); bool member(int) const; }; # endif ` – jayboiq Oct 26 '20 at 05:59
  • Looks like the last line of Node::insert(int should be right -> insert(obj); – Ian4264 Oct 26 '20 at 06:44

0 Answers0