I'm working with a binary tree, and I'm kinda stuck in recursion hell. Here's the algorithm in C++:
Now, here's what happens. I can completely traverse the tree with an inorder Traversal. No problems. However, the pointer returnval should point to the nth node(which is stopspot). But it doesn't. Once it traverses completely the left tree of the root, nodecount has a value, such as 3 or 7, something like that. After it is done with the root's lefttree, then it processes the root, and at the moment, nodecount is set to 1. It's like I never even traversed the left subtree of the root. Any suggestions to keep this from happening. since it's a traversal algorithm...I don't think I can use any return values successfully for each function, so I have to keep passing nodecount as a function paramter so that each time the function is called, I can retain the value. But the value is not actually retained. Please help me, I'm so confused by this phenomena.
Code:
template <class T>
node<T>::inOrderTraversal(int stopspot, node<T>* current, node<T>* returnval, int nodecount)
{
if (current->value){
if (current->leftchild){
current = current->leftchild;
}
nodecount++;
if (nodecount == stopspot) { returnval = current; }
if (current->rightchild){
current = current->rightchild;
}
}
}
Now, here's what happens. I can completely traverse the tree with an inorder Traversal. No problems. However, the pointer returnval should point to the nth node(which is stopspot). But it doesn't. Once it traverses completely the left tree of the root, nodecount has a value, such as 3 or 7, something like that. After it is done with the root's lefttree, then it processes the root, and at the moment, nodecount is set to 1. It's like I never even traversed the left subtree of the root. Any suggestions to keep this from happening. since it's a traversal algorithm...I don't think I can use any return values successfully for each function, so I have to keep passing nodecount as a function paramter so that each time the function is called, I can retain the value. But the value is not actually retained. Please help me, I'm so confused by this phenomena.