Reputation: 95
I'm trying to recursively call my Preorder and Reverse Preorder methods. The methods work over a array-based binary tree, they are supposed to return the length of all the elements of a subtree. But they do is return the length of the first element of the subtree. If anyone can help it'd be appreciated.
int left_width(vector<string>& vec, int i, int ret) {
int left = i * 2 + 1;
int right = i * 2 + 2;
ret = ret + vec[i].length();
if (left < (int)vec.size() && right <= (int)vec.size()) {
left_width(vec, left, ret);
left_width(vec, right, ret);
}
return ret;
}
int right_width(vector<string>& vec, int i, int ret) {
int right = i * 2 + 2;
int left = i * 2 + 1;
ret = ret + vec[i].length();
if (left < (int)vec.size() && right <= (int)vec.size()) {
right_width(vec, right, ret);
right_width(vec, left, ret);
}
return ret;
}
Upvotes: 0
Views: 466
Reputation: 17956
If I understood what you're doing correctly, you need to capture the return values from your calls to left_width
or right_width
to pass along, so you accumulate across all calls. For example:
int right_width(vector<string>& vec, int i, int ret) {
int right = i * 2 + 2;
int left = i * 2 + 1;
ret = ret + vec[i].length();
if (left < (int)vec.size() && right <= (int)vec.size()) {
ret = right_width(vec, right, ret);
ret = right_width(vec, left, ret);
}
return ret;
}
Of course, passing a "continuing return value" in as an argument to thread it through the computation really isn't idiomatic recursion. Usually you do something more like this:
int right_width(vector<string>& vec, int i) {
int right = i * 2 + 2;
int left = i * 2 + 1;
int ret = vec[i].length();
if (left < (int)vec.size() && right <= (int)vec.size()) {
ret += right_width(vec, right);
ret += right_width(vec, left);
}
return ret;
}
Here, you just sum up all the return values from the recursive calls, along with your own local value, and return it back to the caller. No need to pass the work-in-progress counts down to the callees.
Upvotes: 2