Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

methods of all the elements on a given level of a binary tree

parapara Member Posts: 2
Hello
I know of only one method of visiting the elements on one level of a tree. This method is not very efficient. This is the way I do it(PHP implementation):
[code]
private function NextNode(&$node,$curlevel,$desiredlevel,&$nodesnr=null)
{
if($node == null)
return;
$curlevel++;

if($curlevel == $desiredlevel)
{
$this->Visit($node);
if($nodesnr!==null)
$nodesnr++;
}

$this->NextNode($node->left,$curlevel,$desiredlevel,$nodesnr);
$this->NextNode($node->right,$curlevel,$desiredlevel,$nodesnr);
}
[/code]
I travese all the nodes of the tree in depth(inorder) and I check if teh level is equal to my desired level and if so I visit that node. I also keep track on the number of nodes but that is not relevant to the question.
This is inefficient because it goes throgh the entire tree.

Does anyone know of a better(more efficient) sollution?
Thank you in advance
Sign In or Register to comment.