void BinarySearchTree::insert(int d)
{
tree_node* t = new tree_node;
tree_node* parent;
t->data = d;
t->left = NULL;
t->right = NULL;
parent = NULL;
// is this a new tree?
if(isEmpty()) root = t;
else
{
//Note: ALL insertions are as leaf nodes
tree_node* curr;
curr = root;
// Find the Node's parent
while(curr)
{
parent = curr;
if(t->data > curr->data) curr = curr->right;
else curr = curr->left;
}
if(t->data < parent->data)
parent->left = t;
else
parent->right = t;
}
}
Questions:
-
Why do I need to allocate memory for tree_node* t; using new but not for tree_node* parent;?
-
What exactly is tree_node* what does it look like in memory and what does it do?
-
Can someone explain to me the -> operator and how it works?
You don’t need to, but it’s part of the logic.
trepresents the new node you’re inserting, so you need to create it first (which is done by thenew). You don’t allocate memory forparentbecause it will refer to an already existing node:No way to tell (it should be defined somewhere), but it’s probably a structure like so:
It’s for accessing object members through a pointer. If you have
Class* x, thenx->ais equivalent to(*x).a.