Hi this is a code from my SearchTree class. Node* is a structure whith m_info type int, and m_left(smaller nodes by info) and m_right(bigger nodes by info)
void SearchTree::insert(const int &x) {
Node* tempo = m_root;
while (tempo != nullptr) {
if (tempo->m_info >= x) {
tempo = tempo->m_left;
} else {
tempo = tempo->m_right;
}
}
tempo = new Node(x);
}
I am trying to insert a new node to the tree. But looks like I am missing something in memory management. There tempo is a pointer to a new node, however it is not being related to m_root. I am confused here. I really love the power of c++ but it bends my logic.
What am I missing here?
You keep advancing tempo until it is equal to nullptr. At this point you have left the tree and all you have in hand is a pointer into nothingness. Note that in particular the program has no way of determining which node you last visited that led to tempo becoming null.
What you need to do instead is stop one step earlier: While tempo is still pointing to a node, but the next step would make it point to null. Now you still have a valid node of the tree in your hand and can attach the newly allocated node to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With