All right, so I was finishing up a BS Tree today and I came across an odd logical error that I cannot figure out. The recursion isn't working and I'm not sure why.
template <class T>
struct treenode
{
// Variable Declarations
treenode<T>* m_left; // Left Child
treenode<T>* m_right; // Right Child
T m_data; // Data
// Member Functions
treenode(treenode<T>* left = NULL,
treenode<T>* right = NULL): m_left(left), m_right(right) {};
treenode(const treenode<T>& cpy)
{
m_left = cpy.m_left;
m_right = cpy.m_right;
m_data = cpy.m_data;
}
MyBSTree<T>* convert()
{
returnnew MyBSTree<T>(m_data, m_left, m_right);
}
};
and a class MyBSTree which had a single member variable, a point to a treenode<T>.
When I output the tree with T = int, I get
1 2 3 4 5
9
7
5
for
1 2 3
t.insert(7);
t.insert(9);
t.insert(5);
Any number of insertions past this will yield the same output so I know something must be wrong with the insert (or print) function. However, I think it is my insert function because the print function is too simple for a bug like this to occur. Furthermore, if it was the print function, only the deepest degree of the tree wouldn't print. Thus, the insert function.
Erm.. You insert the new elements into a completely unconnected tree created by convert (also causing a memory leak in the process.) And by unconnected I mean there is nothing in the original tree connecting it to the tree created by convert.
I see. The problem, though, is that most of the work is done through a treenode but the calling object for the function is a MyBSTree. So I'm at a loss for how I would make this function work.