Reputation: 81
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.
Upvotes: 6
Views: 4560
Reputation: 18404
Just a little trick will do:
Replace:
void add(Ternary* t, string s, int i)
With:
void add(Ternary*& t, string s, int i)
That's cleaner than passing and then reading output like this:
tree = add(tree, "bye", 1);
When in C++, make use of their references :) In C you would change the function signature to:
void add(Ternary** t, string s, int i)
and remember to correct t
in relevant places.
Well, C++ is clearly cleaner :)
Upvotes: 0
Reputation: 206659
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);
...
Upvotes: 4