Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Search Tree

struct Ternary {

    char current;
    bool wordend;
    Ternary* left;
    Ternary* mid;
    Ternary* right;
    Ternary(char c='@',Ternary* l=NULL, Ternary* m=NULL, Ternary* r=NULL,bool end=false)
    {
        wordend=end;
        current=c;
        left=l;
        mid=m;
        right=r;
    }
};

void add(Ternary* t, string s, int i) {

    if (t == NULL) {
        Ternary* temp = new Ternary(s[i],NULL,NULL,NULL,false);
        t=temp;
    }

    if (s[i] < t->current) {
        add(t->left,s,i);
    }
    else if (s[i] > t->current) {
        add(t->right,s,i);
    }
    else
    {
        if ( i + 1 == s.length()) {
            t->wordend = true;
        }
        else
        {
            add(t->mid,s,i+1);
        }
    }
}

When I add sequence of words using add() the string are getting printed inside if(t==NULL) segment but tree isn't getting formed i.e nodes are not getting linked.

like image 721
CoderXX Avatar asked Oct 09 '22 14:10

CoderXX


1 Answers

t=temp;

This line has no effect outside of the add() function. The caller's pointer is not updated.

You could change your function to return a Ternary* (return t in this case at the end of it), and change the call sites to:

Ternary *tree = 0;
tree = add(tree, "hello", 1);
tree = add(tree, "bye", 1);
...
like image 194
Mat Avatar answered Oct 13 '22 12:10

Mat