How to iterate for objects with indeterminate nesting

Asked

Viewed 17 times

1

I have a class called Document. Each Document may be the son of a Document or Parent of a Document. Each Document can only have one Parent and can have countless children.

I’m trying to write a function Document->parentLevel() to find out how many levels of hierarchy (maximum) exist below this Document.

For example:

                     Doc1 
       Doc2          Doc3         Doc4
   Doc5    Doc 6
Doc7

When rotating Doc1->parentlevel() the function would return 3, as the largest number of hierarchical levels below it is 3 (Doc2->Doc5->Doc7).

Objects have a function Document->hasChildren() returning true or false if the object has children and a function Document->children() that returns a array with the children of that object.

My code so far:

public function parentLevel($startLevel = 0)
    {
        $level = $startLevel;
        $active = $this;
        while ($active->hasChildren()) {
            $level++;
            foreach ($children as $child) {
                if ($child->hasChildren()) {
                    $level2 = $child->parentLevel();
                    if ($level2 > $level) {
                        $level = $level2;
                    }
                }
            }
        }
        return $level;
    }
  • 1

    You will need to know which nodes are in the largest branch or just the number?

1 answer

2


If you don’t need to know which nodes are part of the bigger business, just do:

public function parentLevel ()
{
    $level = 0;

    if ($this->hasChildren())
    {
        $childrenLevels = [];

        foreach($this->children() as $child)
        {
            $childrenLevels[] = $child->parentLevel();
        }

        $level = max($childrenLevels) + 1;
    }

    return $level;
}

See working on Ideone.

Basically, if the knot has children, it looks for the child that has the highest value of parentLevel and increments by 1, otherwise returns 0.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.