Пример #1
0
 /**
  * Simple recursive visualisation.
  * The first node should be the root.
  * Colors are for linux console, sorry windows guys :p
  *
  * @param Node $node
  * @param string $indent
  * @return string The max indentation
  */
 protected function infixeRender(Node $node, $indent = '')
 {
     if (!$node->isLeaf() && $node->haveChild(Node::POSITION_LEFT)) {
         // Show left side first
         $this->infixeRender($node->getChild(Node::POSITION_LEFT), $indent . '  ');
     }
     echo sprintf('%s%s#%d', $indent, $node->getPosition() == 0 ? '-' : ($node->getPosition() > 0 ? '\\' : '/'), $node->getId());
     echo ' L#' . ($node->haveChild(Node::POSITION_LEFT) ? $node->getChild(Node::POSITION_LEFT)->getId() : '-');
     echo ' R#' . ($node->haveChild(Node::POSITION_RIGHT) ? $node->getChild(Node::POSITION_RIGHT)->getId() : '-');
     echo ' P#' . (null !== $node->getParent() ? $node->getParent()->getId() : '-');
     echo ' C:' . (Node::COLOR_RED === $node->getColor() ? "RED" : "BLACK");
     echo PHP_EOL;
     if (!$node->isLeaf() && $node->haveChild(Node::POSITION_RIGHT)) {
         // Show left side first
         $this->infixeRender($node->getChild(Node::POSITION_RIGHT), $indent . '  ');
     }
 }
Пример #2
0
 /**
  * @param Node $node
  * @param int $position
  * @param Node|null $relative
  * @return Node
  */
 public function findRelative(Node $node, $position, Node $relative = null)
 {
     // If we have already seek deeper and found a leaf, return the leaf
     if (null !== $relative && $node->isLeaf()) {
         return $node;
     }
     // If we have a child at this position, go seek to this child opposite direction until find a leaf
     if ($node->haveChild($position)) {
         // If it's a deep search, don't rotate search order. The closest is the deepest
         return $this->findRelative($node->getChild($position), (null === $relative ? -1 : 1) * $position, $node);
     }
     // It's the parent if parent direction is the same as node, else it's grand parent
     return $node->getPosition() === -$position ? $node->getParent() : $node->getGrandParent();
 }