Triple 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 a sequence of words using add(), the line is printed inside if(t==NULL), but the tree is not formed. Nodes are not connected.

+5
source share
2 answers
t=temp;

This line is not valid outside the function add(). Caller ID is not updated.

You can change your function to return Ternary*(return tin this case at the end of this) and change the call sites to:

Ternary *tree = 0;
tree = add(tree, "hello", 1);
tree = add(tree, "bye", 1);
...
+4
source

Only a little trick will do:

Replace:

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

WITH

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

This is cleaner than passing and then reading the output as follows:

tree = add(tree, "bye", 1);

++ :) C :

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

t .

, ++ :)

0

All Articles