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

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):
private function NextNode(&$node,$curlevel,$desiredlevel,&$nodesnr=null)
if($node == null)

if($curlevel == $desiredlevel)

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


  • I would make the variables $curlevel, $desiredlevel and $nodesnr class variables to reduce stack usage, as stack movements is a major slowdown.

    Also, there is no need to traverse behond your desired level, so when you reach that level stop traversing. This requires you to increase the curlevel when you enter the function, and decrease when you exit.

    But, the fact is. If you want all the leaf nodes of a tree, then you need to traverse the entire tree. The only way arround this would be a second order list of leaf nodes.

    Im also unsure why you send *node by reference. It means a function could stuff up your tree structure if it changes $node, which is bad.

    private function NextNod($node)
    if($node) {
    if($this->curlevel == $this->desiredlevel) {
    if($this->nodesnr !== null) $this->nodesnr++;
    } else
Sign In or Register to comment.

Howdy, Stranger!

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


In this Discussion