Originally Posted by
peripatein
Hi,
I wrote the following recursion for finding the distance between a root and a leaf, but am not quite sure how to make it work. Could anyone advise?
Code:
int calc_depth(Node* tree, Node* zero)
{
if (!tree)
return 0;
if (zero->right || zero->left == tree)
return 1;
return (zero->right ? calc_depth(tree, zero->right) : calc_depth(tree, zero->left));
}
Code:
/*
calculate the depth of node node.
Tree has members right and left
*/
int calc_depth(Node *root, Node *node)
{
int ldepth, rddepth;
if(root == 0)
return 0;
if(root == node)
return 1;
ldepth = calc_depth(root->left, node);
rdepth = calc_depth(root->right, node);
if(ldepth)
return ldepth + 1;
if(rdepth)
return rdepth +1;
/* node not on this sub-branch */
return 0;
}
This searches virtually the whole tree, so it's not the most efficient way of doing it. But it's easy.