-
Binary Tree Problems
I followed a textbook example of how to implement a binary tree using template classes, but have needed to modify the (private) insert function to accept another treeNode * for the parent (I want to be able to remove nodes later), but the debugger has trouble getting past aRoot = new treeNode. With the first node, root points to 0 and Eclipse debugger says &aRoot = @0x0. I think it is trying to read memory from address 0 when it shouldn't be. Where I test if aRoot is 0, the program terminates if I don't use (&aRoot == 0). It used to work, but I cannot figure out what is wrong.
Code:
if (&aRoot == 0) { // was if (aRoot == 0) in the book
Code:
template<class treeElement>
bool binaryTree<treeElement>::insert(const treeElement &el) {
treeNode *parent = 0;
return insert(root, el, parent);
}
template<class treeElement>
bool binaryTree<treeElement>::insert(treeNode *&aRoot, const treeElement &el,
treeNode *parent) {
if (&aRoot == 0) {
aRoot = new treeNode;
aRoot->left = 0; //doesn't execute
aRoot->right = 0;
aRoot->info = el;
aRoot->parent = parent;
return true;
}
else if (el == aRoot->info) return false;
else if (el <= aRoot->info)
return insert(aRoot->left, el, aRoot);
else return insert(aRoot->right, el, aRoot);
}
-
Is treeNode supposed to be a template class too? (Edit: I'm guessing here based on the fact that new Treenode seems to be the problem.)
-
treeNode is a struct for the internal representation of the class binaryTree. treeNode contains three treeNode pointers and info of type treeElement (the type that you specify when you create each instance of the class). root is also a treeNode*.