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.
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);
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With