protected function createTree(array $segments) : array
    {
        $nodes = array_map(function (TextSegment $segment) {
            $text = new TextNode($segment->getText());

            // Wrap text node in each tag from the innermost to the outermost.
            $tags = array_reverse($segment->getTags());
            return array_reduce($tags, function (Node $child, Tag $tag) {
                return new TagNode($tag, [$child]);
            }, $text);
        }, $segments);

        return $this->optimizeTree($nodes);
    }