Reputation: 11
I keep getting an error for invalid operand in return expression, I'm trying to recursively code a function to take every value in two different trees and add them together to create one tree but I keep getting an error, any help would be greatly appreciated!
node_t * addTree(node_t * t1, node_t * t2)
{
if(t1 != NULL || t2 != NULL)
{
t1->data = t1->data + t2->data;
return addTree(t1=t1->rightchild, t2=t2->rightchild)+addTree(t1=t1->rightchild, t2=t2->leftchild)+addTree(t1=t1->leftchild, t2=t2->rightchild)+addTree(t1=t1->leftchild, t2=t2->leftchild);
}
else
return t1;
}
Upvotes: 0
Views: 36
Reputation: 87416
Something like this should work. It uses a little trick so we only need a few null checks instead of many.
node_t * addTree(const node_t * t1, const node_t * t2)
{
if (t1 == NULL && t2 == NULL) { return NULL; }
const node_t nullNode = {};
if (t1 == NULL) { t1 = &nullNode; }
if (t2 == NULL) { t2 = &nullNode; }
node_t * r = malloc(sizeof(node_t));
r->data = t1->data + t2->data;
r->leftchild = addTree(t1->leftchild, t2->leftchild);
r->rightchild = addTree(t1->rightchild, t2->rightchild);
return r;
}
Upvotes: 1