protected function nodeSet($key, $value, ?RedBlackNode $node): RedBlackNode
    {
        if ($node === null) {
            return new RedBlackNode($key, $value, 1, RedBlackNode::RED);
        }

        $comp = $this->comparator->compare($key, $node->key());

        if ($comp < 0) {
            $node->setLeft($this->nodeSet($key, $value, $node->left()));
        } elseif ($comp > 0) {
            $node->setRight($this->nodeSet($key, $value, $node->right()));
        } else {
            $node->setValue($value);
        }

        return $this->balanceOnInsert($node);
    }