*/ public function children() : Traversable { if ($this->left) { yield $this->left; } if ($this->right) { yield $this->right; } } /** * Return the left child node. * * @return BinaryNode|null */ public function left() : ?BinaryNode { return $this->left; } /** * Return the right child node. * * @return BinaryNode|null */ public function right() : ?BinaryNode { return $this->right; } /** * Recursive function to determine the height of the node in the tree. * * @return int */ public function height() : int { return 1 + max( $this->left ? $this->left->height() : 0, $this->right ? $this->right->height() : 0 ); } /** * The balance factor of the node. Negative numbers indicate a lean to the left, positive * to the right, and 0 is perfectly balanced. * * @return int */ public function balance() : int { return ($this->right ? $this->right->height() : 0) - ($this->left ? $this->left->height() : 0); } /** * Set the left child node. * * @param BinaryNode|null $node */ public function attachLeft(?BinaryNode $node = null) : void { $this->left = $node; } /** * Set the right child node. * * @param BinaryNode|null $node */ public function attachRight(?BinaryNode $node = null) : void { $this->right = $node; } }