I don't understand why **ptr is used in this code. Please expain to me.
template<class NODETYPE>
void Tree<NODETYPE>::insertNode(const NODETYPE &value)
{ insertNodeHelper(&rootPtr, value); }
template<class NODETYPE>
void Tree<NODETYPE>::insertNodeHelper(TreeNode<NODETYPE> **ptr, const NODETYPE &value)
{
if(*ptr == 0)
*ptr = new TreeNode<NODETYPE>(value);
else
{
if(value < (*ptr)->data)
insertNodeHelper(&((*ptr)->leftPtr), value);
else if(value > (*ptr)->data)
insertNodeHelper(&((*ptr)->rightPtr), value);
else
cout << value << " dup" << endl;
}
}
Why couldn't *ptr be used? I tried and it doesn't insert any nodes.
template<class NODETYPE>
void Tree<NODETYPE>::insertNode(const NODETYPE &value)
{ insertNodeHelper2(rootPtr, value); }
template<class NODETYPE>
void Tree<NODETYPE>::insertNodeHelper2(TreeNode<NODETYPE> *ptr, const NODETYPE &value)
{
if(ptr == 0)
ptr = new TreeNode<NODETYPE>(value);
else
{
if(value < ptr->data)
insertNodeHelper2(ptr->leftPtr, value);
else if(value > ptr->data)
insertNodeHelper2(ptr->rightPtr, value);
else
cout << value << " dup" << endl;
}
}
All my gratefulness.