Skip to content

Commit

Permalink
Add a NodeInterface::height() method and its tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Dec 30, 2018
1 parent b6bcc23 commit 1218e1e
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
33 changes: 33 additions & 0 deletions spec/drupol/phptree/Node/NodeSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -234,4 +234,37 @@ public function it_can_get_its_depth()
->depth()
->shouldReturn(4);
}

public function it_can_get_its_height()
{
$this
->height()
->shouldReturn(0);

$tree = $this;
foreach (\range('A', 'B') as $key => $v) {
$node = new \drupol\phptree\Node\ValueNode($v, 1);
$tree->add($node);
$tree = $node;
}

$this
->height()
->shouldReturn(2);

foreach (\range('C', 'F') as $key => $v) {
$node = new \drupol\phptree\Node\ValueNode($v, 1);
$tree->add($node);
$tree = $node;
}

$this
->height()
->shouldReturn(6);

$this
->withChildren()
->height()
->shouldReturn(0);
}
}
14 changes: 14 additions & 0 deletions src/Node/Node.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,4 +177,18 @@ public function depth(): int
{
return \iterator_count($this->getAncestors());
}

/**
* {@inheritdoc}
*/
public function height(): int
{
$height = $this->depth();

foreach ($this->children() as $child) {
$height = \max($height, $child->height());
}

return $height;
}
}
8 changes: 8 additions & 0 deletions src/Node/NodeInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,14 @@ public function degree(): int;
*/
public function depth(): int;

/**
* Get the tree height.
*
* @return int
* The tree height.
*/
public function height(): int;

/**
* Get a clone of the object with or without children.
*
Expand Down

0 comments on commit 1218e1e

Please sign in to comment.