my idea is simply have a function that checks the id of a node by taking it's pointer => nodeID
Then I traverse the tree until it found nodeID(tree pointer) == id. Then I calculate the depth by using ldepth and rdepth.
Initially i intend to do it in 1 function using recursion, but failed to do so.
So i used 2 functions,1 doing the recursion and another just takes the result and process.
However, it never really worked
Code:
int nodeDepth(CPPtr tree, int id)
{
int lDepth=0,rDepth=0;
nodeDepth_Helper(tree,id,lDepth,rDepth);
cout<<"lDepth "<<lDepth<<endl;
cout<<"rDepth "<<rDepth<<endl;
return min(lDepth,rDepth);
}
//Define nodeDepth_Helper to do the actual recursion to find lDepth and rDepth
void nodeDepth_Helper(CPPtr tree, int id, int& lDepth,int& rDepth)
{
if (tree != NULL)
{
if (nodeID(tree)==id)
return;
else
{
lDepth=lDepth+1;
nodeDepth_Helper(tree->left,id,lDepth,rDepth);
rDepth=rDepth+1;
nodeDepth_Helper(tree->right,id,lDepth,rDepth);
}
}
}